forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSelectionSort.java
More file actions
38 lines (34 loc) · 956 Bytes
/
SelectionSort.java
File metadata and controls
38 lines (34 loc) · 956 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
31
32
33
34
35
36
37
38
package com.examplehub.sorts;
import com.examplehub.utils.SortUtils;
public class SelectionSort implements Sort {
@Override
public void sort(int[] numbers) {
for (int i = 0; i < numbers.length - 1; ++i) {
int minIndex = i; /* index of min value */
for (int j = i + 1; j < numbers.length; ++j) {
if (numbers[j] < numbers[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
SortUtils.swap(numbers, i, minIndex);
}
}
}
@Override
public <T extends Comparable<T>> void sort(T[] array) {
for (int i = 0; i < array.length - 1; ++i) {
int minIndex = i; /* index of min value */
for (int j = i + 1; j < array.length; ++j) {
if (array[j].compareTo(array[minIndex]) < 0) {
minIndex = j;
}
}
if (minIndex != i) {
T temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
}
}