Selection sort in Java

Selection sort is a combination of searching (search for smaller element) and sorting (Swap with first element) and move on. During each pass unsorted element with the smallest value will be swapped to its proper position. Number of times the loop passes through the array will be one less than the size of array (N-1 times). 
In selection sort we need to 2 loops as same as bubble sort, where here inner loop will find the smallest element and outer loop need to swap with the other element and need to place it in proper position. Now lets see simple Java code for selection sort.
Selection sort in Java


public class SelectionSort {

 public static void main(String[] args) {
  int array[] = {3,4,8,5,1,7,9,2,6};
  System.out.print("Array before sorting : ");
  printArray(array);
  
  selectionSort(array);
  
  System.out.print("Array after sorting : ");
  printArray(array);
 }

 public static void selectionSort(int[] values) {
  for (int i = values.length - 1; i > 0; i--) {
   int first = 0; 
   for (int j = 1; j <= i; j++) {
    if (values[j] > values[first])
     first = j;
   }
   int tmp = values[first]; 
   values[first] = values[i];
   values[i] = tmp;
  }
 }
 
 public static void printArray(int[] array) {
  for (int i : array) {
   System.out.print(i + ", ");
  }
  System.out.println();
 }
}



OUTPUT:


Array before sorting : 3, 4, 8, 5, 1, 7, 9, 2, 6, 
Array after sorting : 1, 2, 3, 4, 5, 6, 7, 8, 9, 



No comments :

Post a Comment