-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSelection.java
More file actions
43 lines (38 loc) · 1.06 KB
/
Copy pathSelection.java
File metadata and controls
43 lines (38 loc) · 1.06 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
public class Selection
{
/* An implementation of Selection sort*/
public static void sort(Comparable[] a)
{
// O(N2/2) compares and O(N) exchanges
int N = a.length;
for (int i = 0; i < N; i++)
{
// Array to the left is sorted
// Get minimum element on right and swap
int min = i;
for (int j = i+1; j < N; j++)
if (less(a[j], a[i]))
min = j;
// put minimum in place
exch(a, i, min);
}
assert isSorted(a, 0, a.length-1);
}
protected static boolean less(Comparable p, Comparable q)
{
return p.compareTo(q) < 0;
}
protected static void exch(Comparable[] a, int i, int j)
{
Comparable swap = a[i];
a[i] = a[j];
a[j] = swap;
}
protected static boolean isSorted(Comparable[] a, int lo, int hi)
{
for (int i = lo; i < hi; i++)
if (less(a[i+1], a[i]))
return false;
return true;
}
}