Selection Sorting in Java Program with Example

How does Selection Sort work?

Selection Sort implements a simple sorting algorithm as follows:
  • Algorithm repeatedly searches for the lowest element.
  • Swap current element with an element having the lowest value
  • With every iteration/pass of selection sort, elements are swapped.


Java Program to implement Selection Sort

  1. package com.guru99;
  2. public class SelectionSortAlgo {
  3.  
  4. public static void main(String a[])
  5. {
  6. int[] myArray = {860,8,200,9};
  7. System.out.println("------Before Selection Sort-----");
  8. printArray(myArray);
  9. selection(myArray);//sorting array using selection sort
  10. System.out.println("-----After Selection Sort-----");
  11. printArray(myArray);
  12. }
  13. public static void selection(int[] array)
  14. {
  15. for (int i = 0; i < array.length - 1; i++)
  16. { System.out.println("Sort Pass Number "+(i+1));
  17. int index = i;
  18. for (int j = i + 1; j < array.length; j++)
  19. {
  20. System.out.println("Comparing "+ array[index] + " and " + array[j]);
  21. if (array[j] < array[index]){
  22. System.out.println(array[index] + " is greater than " + array[j] );
  23. index = j;
  24. }
  25. }
  26. int smallerNumber = array[index];
  27. array[index] = array[i];
  28. array[i] = smallerNumber;
  29. System.out.println("Swapping Elements: New Array After Swap");
  30. printArray(array);
  31. }
  32. }
  33. static void printArray(int[] array){
  34. for(int i=0; i < array.length; i++)
  35. {
  36. System.out.print(array[i] + " ");
  37. }
  38. System.out.println();
  39. }
  40. }

Output:

------Before Selection Sort-----
860 8 200 9 
Sort Pass Number 1
Comparing 860 and 8
860 is greater than 8
Comparing 8 and 200
Comparing 8 and 9
Swapping Elements: New Array After Swap
8 860 200 9 
Sort Pass Number 2
Comparing 860 and 200
860 is greater than 200
Comparing 200 and 9
200 is greater than 9
Swapping Elements: New Array After Swap
8 9 200 860 
Sort Pass Number 3
Comparing 200 and 860
Swapping Elements: New Array After Swap
8 9 200 860 
-----After Selection Sort-----
8 9 200 860 

No comments:

Post a Comment