Selection sort
Selection sort is conceptually the most simplest sorting algorithm. This algorithm will first find the smallest element in the array and swap it with the element in the first position, then it will find the second smallest element and swap it with the element in the second position, and it will keep on doing this until the entire array is sorted. It is called selection sort because it repeatedly selects the next-smallest element and swaps it into the right place. |
public class SelectionSort { public static void main(String[] args) { int[] arr = { 4, 14, 6, 15, 8, 0, 313, 80, 21, 67, 81, 142 }; printArray(arr, "BEFORE SORTING : "); selectionSort(arr); printArray(arr, "AFTER SORTING : "); } public static void selectionSort(int[] arr) { for (int i = 0; i < arr.length; i++) { int minIndex = i; for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } if (minIndex != i) { int tmp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = tmp; } } } public static void printArray(int[] arr, String msg) { System.out.print(msg); for (int i : arr) { System.out.print(i + ", "); } System.out.println(); } }
OUTPUT:
BEFORE SORTING : 4, 14, 6, 15, 8, 0, 313, 80, 21, 67, 81, 142, AFTER SORTING : 0, 4, 6, 8, 14, 15, 21, 67, 80, 81, 142, 313,