-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathQuick.java
More file actions
72 lines (57 loc) · 1.66 KB
/
Copy pathQuick.java
File metadata and controls
72 lines (57 loc) · 1.66 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
public class Quick {
public static void sort(Comparable[] a) {
StdRandom.shuffle(a);
sort(a, 0, a.length - 1);
assert isSorted(a);
}
public static void sort(Comparable[] a, int lo, int hi) {
if (lo >= hi)
return;
int j = partition(a, lo, hi);
sort(a, lo, j - 1);
sort(a, j + 1, hi);
}
public static int partition(Comparable[] a, int lo, int hi) {
int i = lo;
int j = hi + 1;
Comparable v = a[lo];
while (true) {
while (less(a[++i], v))
if (i == hi) break;
while(less(v, a[--j]))
if (j == lo) break;
if (i >= j) break;
exch(a, i, j);
}
exch(a, lo, j);
return j;
}
public static boolean less(Comparable a, Comparable b) {
return (a.compareTo(b) < 0);
}
public static boolean isSorted(Comparable[] a) {
return isSorted(a, 0, a.length - 1);
}
public static boolean isSorted(Comparable[] a, int lo, int hi) {
for (int i = lo + 1; i <= hi; i++)
if (less(a[i - 1], a[i]))
return false;
return true;
}
public static void exch(Object[] a, int i, int j) {
Object tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
public static void show(Comparable[] a) {
StdOut.println("\nshow():");
for (int i = 0; i < a.length; i++)
StdOut.println("a[" + i + "] = " + a[i]);
}
public static void main(String[] args) {
String[] str = {"A", "M", "D", "G", "E", "X"};
show(str);
sort(str);
show(str);
}
}