forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
30 lines (27 loc) · 948 Bytes
/
SelectionSort.java
File metadata and controls
30 lines (27 loc) · 948 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.thealgorithms.sorts;
public class SelectionSort implements SortAlgorithm {
/**
* Sorts an array of comparable elements in increasing order using the selection sort algorithm.
*
* @param array the array to be sorted
* @param <T> the class of array elements
* @return the sorted array
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
for (int i = 0; i < array.length - 1; i++) {
final int minIndex = findIndexOfMin(array, i);
SortUtils.swap(array, i, minIndex);
}
return array;
}
private static <T extends Comparable<T>> int findIndexOfMin(T[] array, final int startIndex) {
int minIndex = startIndex;
for (int i = startIndex + 1; i < array.length; i++) {
if (array[i].compareTo(array[minIndex]) < 0) {
minIndex = i;
}
}
return minIndex;
}
}