Skip to content

Commit 5801f7d

Browse files
committed
Add QuickSelect for Java
1 parent c481f3e commit 5801f7d

1 file changed

Lines changed: 70 additions & 0 deletions

File tree

QuickSelect/Java/QuickSelect.java

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/**
2+
* Find the kth smallest element in an unordered array.
3+
*
4+
* @author Atom
5+
* @see <a href="https://en.wikipedia.org/wiki/Quickselect">Quickselect</a>
6+
*/
7+
public class QuickSelect {
8+
9+
/**
10+
* Lomuto partition scheme
11+
*
12+
* @param arr
13+
* @param low
14+
* @param high
15+
* @return the pivot's final location
16+
*/
17+
private static <T extends Comparable<? super T>> int partition(final T[] arr, final int low, final int high) {
18+
T pivot = arr[high];
19+
int index = low;
20+
for (int i = low; i < high; i++) {
21+
if (arr[i].compareTo(pivot) <= 0) {
22+
swap(arr, i, index);
23+
index++;
24+
}
25+
}
26+
swap(arr, index, high);
27+
return index;
28+
}
29+
30+
/**
31+
* Find the kth smallest element in an unordered array.
32+
*
33+
* @param arr
34+
* @param kth from 0 to arr.length - 1
35+
* @return kth smallest element
36+
*/
37+
public static <T extends Comparable<? super T>> T select(final T[] arr, final int kth) {
38+
if (kth < 0 || kth > arr.length - 1) throw new IllegalArgumentException("elements in the array = " + arr.length + ", kth(0..length-1) = " + kth);
39+
40+
int left = 0;
41+
int right = arr.length - 1;
42+
while (right >= left) {
43+
int pivotIndex = partition(arr, left, right);
44+
if (kth == pivotIndex) {
45+
return arr[pivotIndex];
46+
} else if (kth < pivotIndex) {
47+
right = pivotIndex - 1;
48+
} else {
49+
left = pivotIndex + 1;
50+
}
51+
}
52+
return null;
53+
}
54+
55+
private static void swap(Object arr[], int i1, int i2) {
56+
if (i1 == i2) { return; }
57+
58+
Object temp = arr[i1];
59+
arr[i1] = arr[i2];
60+
arr[i2] = temp;
61+
}
62+
63+
public static void main(String[] args) {
64+
for (int kth = 0; kth < 10; kth++) {
65+
Integer[] a = { 1, 4, 2, 5, 0, 3, 9, 7, 6, 8 };
66+
System.out.println("kth(" + kth + ") smallest element = " + select(a, kth));
67+
}
68+
}
69+
70+
}

0 commit comments

Comments
 (0)