Selection sort java

Hey guys!! Welcome to flower brackets blog. This post explains selection sort java.

selection sort java

In selection sort sorting algorithm, unsorted (lowest) element is shifted to its correct position in an array.

Also read – insertion sort in java

The selection sort loop continues until the arrangement of integer elements in array in the ascending order.

The number of times the sorting takes place will always be one less than the number of integer elements in an array. It is considered as one of the simplest algorithms. Let’s see java program,

import java.util.Scanner;

public class SelectionSortInJava
{ 
   public static void toSort(int[] array)
   {
      int num = array.length;
      int a;
      int b;
      int place;
      int temp;
      for(a = 0; a < num - 1; a++)
      {
         place = a;
         for(b = a + 1; b < num; b++)
         {
            if(array[b] < array[place])
            {
               place = b;
            }
         }
         temp = array[a];
         array[a] = array[place];
         array[place] = temp;
      }
   }

   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      int x;
      int y;
      // accepting user entered elements
      System.out.println("Please enter number of integer elements");
      x = sc.nextInt();
      // creating array elements
      int arr[] = new int[x];
      System.out.println("Please enter " + x + " integer elements.");
      System.out.println("Elements before sorting : ");
      for(y = 0; y < x; y++)
         arr[y] = sc.nextInt();
 
      // calling toSort method
      toSort(arr);
      // displaying sorted array
      System.out.println("Elements after sorting : ");
      for(y = 0; y < x; y++)
         System.out.print(arr[y] + " ");
         System.out.println();
   }
}

Output:

Please enter number of integer elements: 5
Please enter 5 integer elements.
Elements before sorting : 5 4 -3 2 -1
Elements after sorting : -3 -1 2 4 5


Related Posts