@@ -25,7 +25,6 @@ public <T extends Comparable<T>> T[] sort(T[] array) {
25
25
* @param <T> the type of elements in the array (must be Comparable)
26
26
*/
27
27
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
29
28
if (array == null || array .length == 0 ) {
30
29
return ;
31
30
}
@@ -34,7 +33,7 @@ private static <T extends Comparable<T>> void recursiveSelectionSort(T[] array,
34
33
}
35
34
36
35
// Find the minimum element in the remaining unsorted array
37
- int minIndex = findMinIndex (array , index , index + 1 );
36
+ int minIndex = findMinIndex (array , index );
38
37
39
38
// Swap the found minimum element with the element at the current index
40
39
if (minIndex != index ) {
@@ -46,26 +45,22 @@ private static <T extends Comparable<T>> void recursiveSelectionSort(T[] array,
46
45
}
47
46
48
47
/**
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.
50
49
*
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
56
54
*/
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 ;
62
57
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
+ }
66
62
}
67
63
68
- // Recursively find the minimum element in the rest of the array
69
- return findMinIndex (array , currentMinIndex , currentIndex + 1 );
64
+ return currentMinIndex ;
70
65
}
71
66
}
0 commit comments