-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathSelectionSort.java
More file actions
63 lines (45 loc) · 1.55 KB
/
Copy pathSelectionSort.java
File metadata and controls
63 lines (45 loc) · 1.55 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* This class provides an implementation of the Selection Sort algorithm for
* lists and arrays of any comparable type class
*
* https://de.wikipedia.org/wiki/Selectionsort
*/
public class SelectionSort {
/**Tests the algorithm with an array with Integers ranging from 0 to 99 */
public static void test(){
ArrayList<Integer> testList = new ArrayList<>();
for(int i = 0; i < 100; i++){
testList.add(i);
}
Collections.shuffle(testList);
Integer[] testArray = testList.toArray(new Integer[0]);
sort(testList);
sort(testArray);
System.out.println(testList);
for(int i = 0; i < testArray.length; i++){
System.out.printf("%d ", testArray[i]);
}
}
public static <T extends Comparable<T>> void sort(List<T> toSort){
int highestIndex = toSort.size() - 1;
int insertIndex = 0;
int minPosition;
do{
minPosition = insertIndex;
for(int i = insertIndex + 1; i <= highestIndex; i++){
if(toSort.get(i).compareTo(toSort.get(minPosition)) < 0){
minPosition = i;
}
}
Collections.swap(toSort, minPosition, insertIndex);
insertIndex++;
}while(insertIndex < highestIndex);
}
public static <T extends Comparable<T>> void sort(T[] toSort){
sort(Arrays.asList(toSort));
}
}