forked from OneCodeMonkey/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
96 lines (83 loc) · 2.08 KB
/
SelectionSort.java
File metadata and controls
96 lines (83 loc) · 2.08 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* Selection sort.
*
*/
import java.util.Comparator;
/**
* The `SelectionSort` class provides static methods for sorting an array using
* selection sort.
*
*/
public class Selection {
private Selection() {}
// Rearranges the array in ascending order, using the natural order.
public static void sort(Comparable[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int min = i;
for(int j = i + 1; j < n; j++) {
if(less(a[j], a[min]))
min = j;
}
exchange(a, i, min);
assert isSorted(a, 0, i);
}
assert isSorted(a);
}
// Rearranges the array in ascending order, using a comparator.
public static void sort(Object[] a, Comparable comparator) {
int n = a.length;
for(int i = 0; i < n; i++) {
int min = i;
for(int j = i + 1; j < n; j++) {
if(less(comparator, a[j], a[min]))
min = j;
}
exchange(a, i, min);
assert isSorted(a, comparator, 0, i);
}
assert isSorted(a, comparator);
}
// helper functions
// is v < w ?
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
// is v < w ?
private static boolean less(Comparator comparator, Object v, Object w) {
return comparator.compare(v, w) < 0;
}
// exchange a[i] and a[j]
private static void exchange(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
// check if array is sorted(for debug)
private static boolean isSorted(Comparable[] a) {
return isSorted(a, 0, a.length - 1);
}
private static boolean isSorted(Comparable[] a, int low, int high) {
for(int i = low + 1; i <= high; i++)
if(less(a[i], a[i - 1]))
return false;
return true;
}
private static boolean isSorted(Object[] a, Comparator comparator, int low, int high) {
for(int i = low + 1; i <= high; i++)
if(less(comparator, a[i], a[i - 1]))
return false;
return true;
}
// print
private static void show(Comparable[] a) {
for(int i = 0; i < a.length; i++)
StdOut.println(a[i]);
}
// test
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
SelectionSort.sort(a);
show(a);
}
}