forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeterministicQuickSelect.java
More file actions
84 lines (71 loc) · 2.51 KB
/
DeterministicQuickSelect.java
File metadata and controls
84 lines (71 loc) · 2.51 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
package com.thealgorithms.divideandconquer;
/**
* Deterministic QuickSelect (Median of Medians) algorithm.
*
* Finds the kth smallest element in an unsorted array in O(n) worst-case time.
*
* Reference: https://en.wikipedia.org/wiki/Median_of_medians
*/
public final class DeterministicQuickSelect {
private DeterministicQuickSelect() {
}
public static int select(int[] arr, int k) {
if (arr == null) {
throw new IllegalArgumentException("Input array cannot be null");
}
if (k < 1 || k > arr.length) {
throw new IllegalArgumentException("k is out of bounds");
}
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];
}
int pivotIndex = medianOfMedians(arr, left, right);
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, storeIndex, i);
storeIndex++;
}
}
swap(arr, right, storeIndex);
return storeIndex;
}
private static int medianOfMedians(int[] arr, int left, int right) {
int n = right - left + 1;
if (n <= 5) {
return partition5(arr, left, right);
}
int numMedians = (int) Math.ceil((double) n / 5);
int[] medians = new int[numMedians];
for (int i = 0; i < numMedians; i++) {
int subLeft = left + i * 5;
int subRight = Math.min(subLeft + 4, right);
medians[i] = arr[partition5(arr, subLeft, subRight)];
}
return quickSelect(medians, 0, medians.length - 1, medians.length / 2);
}
private static int partition5(int[] arr, int left, int right) {
java.util.Arrays.sort(arr, left, right + 1);
return (left + right) / 2;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}