Сортировка выбором
Она работает, выбирая наименьший элемент из несортированного подмассива и помещая его на первую позицию этого подмассива (в порядке возрастания). Затем он повторно выбирает следующий наименьший элемент.
2 1 3 5 4 -> 1 is the smallest in unsorted array. 1 2 3 5 4 -> place 1 in the first position of the unsorted sub-array. 1 2 3 5 4 -> 1 2 3 is sorted array, while 4 is the smallest in the unsorted array 5 4. 1 2 3 4 5 -> place 4 in the first position of the sorted sub-array.
[Реализация][Java]
public class SelectionSort { public static int[] sortDesc(int[] inputArr) { for (int i = 0; i < inputArr.length - 1; i++) { for (int j = i + 1; j < inputArr.length; j++) { if (inputArr[i] < inputArr[j]) { swap(inputArr, i, j); } } } return inputArr; } public static int[] sortAsc(int[] inputArr) { for (int i = 0; i < inputArr.length - 1; i++) { for (int j = i + 1; j < inputArr.length; j++) { if (inputArr[i] > inputArr[j]) { swap(inputArr, i, j); } } } return inputArr; } private static void swap(int[] inputArrArr, int i, int j) { int tmp = inputArrArr[i]; inputArrArr[i] = inputArrArr[j]; inputArrArr[j] = tmp; } }