-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathFindKth.java
More file actions
140 lines (120 loc) · 2.75 KB
/
FindKth.java
File metadata and controls
140 lines (120 loc) · 2.75 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package algorithm.basic;
public class FindKth {
/**
* 0-th smallest is the smallest.
*
* @param A
* @param k
* @return
*/
public static int findKth(int[] A, int k) {
if (k <= 0 || k >= A.length) {
throw new IllegalArgumentException(String.format(
"k should be in range [0, %d]\n.", A.length));
}
k = k - 1; // index starts from 0
int start = 0, end = A.length - 1;
int pivot = -1;
while (pivot != k) {
pivot = pivotHoare(A, start, end);
if (pivot < k) {
start = pivot + 1;
} else {
end = pivot - 1;
}
}
return A[pivot];
}
private static int findKth(int[] A, int k, int start, int end) {
int pivot = pivotHoare(A, start, end);
if (pivot == k) {
return A[pivot];
} else if (pivot < k) { // find the (k - pivot)-th from the second half
return findKth(A, k, pivot + 1, end);
} else { // pivot > k, find the k-th from the first half
return findKth(A, k, start, pivot - 1);
}
}
private int pivot(int[] A, int start, int end) {
int pivot = A[end];
int bar = start - 1;
for (int i = start; i < end; ++i) {
if (A[i] < pivot) {
++bar;
int tmp = A[i];
A[i] = A[bar];
A[bar] = tmp;
}
}
int tmp = A[bar + 1];
A[bar + 1] = A[end];
A[end] = tmp;
return bar + 1;
}
private static int pivotHoare(int[] A, int start, int end) {
int i = start, j = end + 1;
int pivot = A[start];
while (true) {
while (A[++i] < pivot) {
if (i == end) {
break;
}
}
while (pivot < A[--j]) {
if (j == start) {
break;
}
}
if (i >= j) {
break;
}
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
// move pivot to appropriate location
int tmp = A[j];
A[j] = A[start];
A[start] = tmp;
return j;
}
public static void median(int[] tokens, int left, int right, int medianIdx) {
int pivot = -1;
while (pivot != medianIdx) {
pivot = partition(tokens, left, right);
if (pivot < medianIdx) {
left = pivot + 1;
} else {
right = pivot - 1;
}
}
System.out.println(tokens[medianIdx]);
}
private static int partition(int[] A, int start, int end) {
int pivot = A[start];
int i = start;
int j = end + 1;
while (true) {
while (A[++i] < pivot) {
if (i == end) {
break;
}
}
while (A[--j] > pivot) {
if (j == start) {
break;
}
}
if (i >= j) {
break;
}
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
int tmp = A[j];
A[j] = A[start];
A[start] = tmp;
return j;
}
}