Skip to main content

Java Selection Sort in Descending Order

 Program in Java to accept any number of elements in an array and sort them is descending order using selection sort.

import java.util.Scanner;
class SelectionSortNumber
{
 public static void main(String args[])
 {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter the number of elements: ");
  int n = sc.nextInt();
  int A[] = new int[n]; //array initialized
  System.out.println("Enter the values into the array:");
  for(int i=0;i<n;i++)
  {
   A[i]=sc.nextInt(); //accepting the values into the array
  }
  //selection sort
  for(int i=0;i<n-1;i++)
  {
   int m=A[i];
   int pos=i;
   for(int j=i+1;j<n;j++)
   {
    if(m<A[j])
    {
     m=A[j]; //find the greatest number index position
     pos=j;
    }
   }
   int t = A[pos];
   A[pos]=A[i]; //store the smallest value in the location
   A[i]=t; // interchange the location
  }

  //display the sorted array
  System.out.println("Elements in descending order are: ");
  for(int i=0;i<n;i++)
  {
   System.out.println(A[i]);
  }
 }
}

Popular posts from this blog