Skip to content

Commit cf0249c

Browse files
author
alxklm
committed
Fix issue with findMinIndex
1 parent 077c6d4 commit cf0249c

File tree

1 file changed

+13
-18
lines changed

1 file changed

+13
-18
lines changed

src/main/java/com/thealgorithms/sorts/SelectionSortRecursive.java

+13-18
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ public <T extends Comparable<T>> T[] sort(T[] array) {
2525
* @param <T> the type of elements in the array (must be Comparable)
2626
*/
2727
private static <T extends Comparable<T>> void recursiveSelectionSort(T[] array, int index) {
28-
// Base case: if the array is null, empty, or index has reached the end of the array, return
2928
if (array == null || array.length == 0) {
3029
return;
3130
}
@@ -34,7 +33,7 @@ private static <T extends Comparable<T>> void recursiveSelectionSort(T[] array,
3433
}
3534

3635
// Find the minimum element in the remaining unsorted array
37-
int minIndex = findMinIndex(array, index, index + 1);
36+
int minIndex = findMinIndex(array, index);
3837

3938
// Swap the found minimum element with the element at the current index
4039
if (minIndex != index) {
@@ -46,26 +45,22 @@ private static <T extends Comparable<T>> void recursiveSelectionSort(T[] array,
4645
}
4746

4847
/**
49-
* Recursively finds the index of the minimum element in the array starting from a given index.
48+
* Finds the index of the minimum element in the array starting from the given index.
5049
*
51-
* @param array the array to search
52-
* @param currentMinIndex the index of the current minimum element
53-
* @param currentIndex the current index being checked
54-
* @param <T> the type of elements in the array (must be Comparable)
55-
* @return the index of the minimum element in the array
50+
* @param array the array to search
51+
* @param start the starting index for the search
52+
* @param <T> the type of elements in the array
53+
* @return the index of the minimum element
5654
*/
57-
private static <T extends Comparable<T>> int findMinIndex(T[] array, int currentMinIndex, int currentIndex) {
58-
// Base case: if the currentIndex has reached the end of the array, return currentMinIndex
59-
if (currentIndex == array.length) {
60-
return currentMinIndex;
61-
}
55+
private static <T extends Comparable<T>> int findMinIndex(T[] array, int start) {
56+
int currentMinIndex = start;
6257

63-
// Update currentMinIndex if the element at currentIndex is smaller
64-
if (array[currentIndex].compareTo(array[currentMinIndex]) < 0) {
65-
currentMinIndex = currentIndex;
58+
for (int currentIndex = start + 1; currentIndex < array.length; currentIndex++) {
59+
if (array[currentIndex].compareTo(array[currentMinIndex]) < 0) {
60+
currentMinIndex = currentIndex;
61+
}
6662
}
6763

68-
// Recursively find the minimum element in the rest of the array
69-
return findMinIndex(array, currentMinIndex, currentIndex + 1);
64+
return currentMinIndex;
7065
}
7166
}

0 commit comments

Comments
 (0)