Skip to main content

Program in Java Selection Sort Ascending order Numbers

Program in Java to implement selection sort (Ascending order)


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 smallest 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 ascending order are: ");
  for(int i=0;i<n;i++)
  {
   System.out.println(A[i]);
  }
 }
}

Popular posts from this blog