-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKthSmallest.java
More file actions
47 lines (39 loc) · 1.28 KB
/
KthSmallest.java
File metadata and controls
47 lines (39 loc) · 1.28 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
import java.util.Random;
class Solution {
public static int kthSmallest(int[] arr, int k) {
return quickSelect(arr, 0, arr.length - 1, k - 1);
}
private static int quickSelect(int[] arr, int left, int right, int k) {
if (left == right) {
return arr[left];
}
Random rand = new Random();
int pivotIndex = left + rand.nextInt(right - left + 1);
pivotIndex = partition(arr, left, right, pivotIndex);
if (k == pivotIndex) {
return arr[k];
} else if (k < pivotIndex) {
return quickSelect(arr, left, pivotIndex - 1, k);
} else {
return quickSelect(arr, pivotIndex + 1, right, k);
}
}
private static int partition(int[] arr, int left, int right, int pivotIndex) {
int pivotValue = arr[pivotIndex];
swap(arr, pivotIndex, right);
int storeIndex = left;
for (int i = left; i < right; i++) {
if (arr[i] < pivotValue) {
swap(arr, i, storeIndex);
storeIndex++;
}
}
swap(arr, storeIndex, right);
return storeIndex;
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}