|
| 1 | +package com.thealgorithms.sorts; |
| 2 | + |
| 3 | +/** |
| 4 | + * Class that implements the Selection Sort algorithm using recursion. |
| 5 | + */ |
| 6 | +public class SelectionSortRecursive implements SortAlgorithm { |
| 7 | + |
| 8 | + /** |
| 9 | + * Sorts an array using recursive selection sort. |
| 10 | + * |
| 11 | + * @param array the array to be sorted |
| 12 | + * @param <T> the type of elements in the array (must be Comparable) |
| 13 | + * @return the sorted array |
| 14 | + */ |
| 15 | + public <T extends Comparable<T>> T[] sort(T[] array) { |
| 16 | + if (array.length == 0) { |
| 17 | + return array; |
| 18 | + } |
| 19 | + recursiveSelectionSort(array, 0); |
| 20 | + return array; |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * Recursively sorts the array using selection sort. |
| 25 | + * |
| 26 | + * @param array the array to be sorted |
| 27 | + * @param index the current index to start sorting from |
| 28 | + * @param <T> the type of elements in the array (must be Comparable) |
| 29 | + */ |
| 30 | + private static <T extends Comparable<T>> void recursiveSelectionSort(T[] array, int index) { |
| 31 | + if (index == array.length - 1) { |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + // Find the minimum element in the remaining unsorted array |
| 36 | + final int minIndex = findMinIndex(array, index); |
| 37 | + |
| 38 | + // Swap the found minimum element with the element at the current index |
| 39 | + if (minIndex != index) { |
| 40 | + SortUtils.swap(array, index, minIndex); |
| 41 | + } |
| 42 | + |
| 43 | + // Recursively call selection sort for the remaining array |
| 44 | + recursiveSelectionSort(array, index + 1); |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Finds the index of the minimum element in the array starting from the given index. |
| 49 | + * |
| 50 | + * @param array the array to search in. |
| 51 | + * @param start the starting index. |
| 52 | + * @param <T> the type of the elements in the array, which must be Comparable. |
| 53 | + * @return the index of the minimum element starting from the given index. |
| 54 | + */ |
| 55 | + private static <T extends Comparable<T>> int findMinIndex(T[] array, int start) { |
| 56 | + int currentMinIndex = start; |
| 57 | + |
| 58 | + for (int currentIndex = start + 1; currentIndex < array.length; currentIndex++) { |
| 59 | + if (array[currentIndex].compareTo(array[currentMinIndex]) < 0) { |
| 60 | + currentMinIndex = currentIndex; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return currentMinIndex; |
| 65 | + } |
| 66 | +} |
0 commit comments