// Basic selection sort with optional sorting direction flag (asc by default). // Sorts given array passed by reference and sorts it. public static void SelectionSort(ref int[] arNumbers, bool sortDesc = false) { for (int i = 0; i < arNumbers.Length - 1; i++) { int index = i; for (int j = i + 1; j < arNumbers.Length; j++) { if (sortDesc) { if (arNumbers[j] > arNumbers[index]) { index = j; } } else { if (arNumbers[j] < arNumbers[index]) { index = j; } } } // If current iteration index is different than // the minimum index found, swap them. if (index != i) { int temp = arNumbers[i]; arNumbers[i] = arNumbers[index]; arNumbers[index] = temp; } } }
Posted: March 19, 2023
Return to the snippets listing