Skip to content

Commit f98d126

Browse files
author
Alex Klymenko
committed
refactor: simplify assign minIndex in recursiveSelectionSort, and improving SelectionSort
1 parent 10314dc commit f98d126

File tree

2 files changed

+14
-27
lines changed

2 files changed

+14
-27
lines changed
Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
package com.thealgorithms.sorts;
22

3-
/**
4-
* This class provides an implementation of the selection sort algorithm.
5-
* It sorts an array of elements in increasing order using an iterative approach.
6-
*/
73
public class SelectionSort implements SortAlgorithm {
84
/**
95
* Sorts an array of comparable elements in increasing order using the selection sort algorithm.
@@ -14,25 +10,22 @@ public class SelectionSort implements SortAlgorithm {
1410
*/
1511
@Override
1612
public <T extends Comparable<T>> T[] sort(T[] array) {
17-
if (array.length == 0) {
18-
return array;
19-
}
20-
2113
// One by one move the boundary of the unsorted subarray
2214
for (int i = 0; i < array.length - 1; i++) {
23-
// Find the minimum element in the unsorted array
24-
int minIndex = i;
25-
for (int j = i + 1; j < array.length; j++) {
26-
if (array[j].compareTo(array[minIndex]) < 0) {
27-
minIndex = j;
28-
}
29-
}
3015

31-
// Swap the found minimum element with the first element
32-
if (minIndex != i) {
33-
SortUtils.swap(array, i, minIndex);
34-
}
16+
// Swap the remaining minimum element with the current element
17+
SortUtils.swap(array, i, findIndexOfMin(array, i));
3518
}
3619
return array;
3720
}
38-
}
21+
22+
private static <T extends Comparable<T>> int findIndexOfMin(T[] array, final int start) {
23+
int minIndex = start;
24+
for (int i = start + 1; i < array.length; i++) {
25+
if (array[i].compareTo(array[minIndex]) < 0) {
26+
minIndex = i;
27+
}
28+
}
29+
return minIndex;
30+
}
31+
}

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

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,7 @@ private static <T extends Comparable<T>> void recursiveSelectionSort(T[] array,
3232
return;
3333
}
3434

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-
}
35+
SortUtils.swap(array, index, findMinIndex(array, index));
4236

4337
// Recursively call selection sort for the remaining array
4438
recursiveSelectionSort(array, index + 1);

0 commit comments

Comments
 (0)