-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuick3string.java
More file actions
81 lines (70 loc) · 2.14 KB
/
Copy pathQuick3string.java
File metadata and controls
81 lines (70 loc) · 2.14 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
/*
* Sample usage: java Quick3string < words3.txt
* Sample usage: java Quick3string < shells.txt
*/
public class Quick3string {
private static final int M = 15; // cutoff for small subarrays
private static void sort(String[] a, int lo, int hi, int d){
if (hi <= lo+M){
insertionSort(a, lo, hi, d);
return;
}
// a[lo..lt-1] < v
// a[gt+1..hi] > v
// a[lt..i] == v
// a[i+1..gt] not yet examined
int lt = lo, i = lo+1, gt = hi;
int v = charAt(a[lo], d);
while (i <= gt) {
int t = charAt(a[i], d);
if (t < v) {
exch(a, lt, i);
lt++;
i++;
}
else if (t > v) {
exch(a, i, gt);
gt--;
}
else {
i++;
}
} // Now a[lo..lt-1] < v = a[lt..gt] < a[gt+1..hi].
sort(a, lo, lt-1, d);
if (v >= 0) sort(a, lt, gt, d+1);
sort(a, gt+1, hi, d);
}
public static void sort(String[] a){
StdRandom.shuffle(a); // Eliminate dependence on input.
sort(a, 0, a.length-1, 0);
}
// return dth character of s, -1 if d = length of string
private static int charAt(String s, int d){
if (d<s.length())
return s.charAt(d);
else
return -1;
}
private static void insertionSort(String[] a, int lo, int hi, int d){
// Sort from a[lo] to a[hi], starting at the dth character.
for (int i=lo; i<=hi; i++)
for (int j=i; j>lo && less(a[j], a[j-1], d); j--)
exch(a, j, j-1);
}
private static boolean less(String v, String w, int d){
return v.substring(d).compareTo(w.substring(d)) < 0;
}
private static void exch(String[] a, int i, int j){
String t = a[i];
a[i] = a[j];
a[j] = t;
}
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
int n = a.length;
sort(a);
for (int i = 0; i < n; i++)
StdOut.print(a[i] + " ");
StdOut.println();
}
}