Skip to content

Commit e81bdf6

Browse files
jasonsaruuloSaruul Shafiq
and
Saruul Shafiq
authored
Added quick select. (williamfiset#272)
Co-authored-by: Saruul Shafiq <[email protected]>
1 parent 412440a commit e81bdf6

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package com.williamfiset.algorithms.sorting;
2+
3+
public class QuickSelect {
4+
5+
public Integer quickSelect(int[] ar, int k) {
6+
if (ar == null) return null;
7+
if (k > ar.length) return null;
8+
if (k < 1) return null;
9+
return quickSelect(ar, k, 0, ar.length - 1);
10+
}
11+
12+
// Sort interval [lo, hi] inplace recursively, returns value when splitPoint == k - 1
13+
private static Integer quickSelect(int[] ar, int k, int lo, int hi) {
14+
int index = k - 1;
15+
if (lo < hi) {
16+
int splitPoint = partition(ar, lo, hi);
17+
if (splitPoint == index) {
18+
return ar[splitPoint];
19+
} else if (splitPoint > index) {
20+
return quickSelect(ar, k, lo, splitPoint);
21+
}
22+
return quickSelect(ar, k, splitPoint + 1, hi);
23+
}
24+
return ar[lo];
25+
}
26+
27+
// Performs Hoare partition algorithm for quick select, taken from QuickSelect implementation
28+
private static int partition(int[] ar, int lo, int hi) {
29+
int pivot = ar[lo];
30+
int i = lo - 1, j = hi + 1;
31+
while (true) {
32+
do {
33+
i++;
34+
} while (ar[i] < pivot);
35+
do {
36+
j--;
37+
} while (ar[j] > pivot);
38+
if (i < j) swap(ar, i, j);
39+
else return j;
40+
}
41+
}
42+
43+
// Swap two elements
44+
private static void swap(int[] ar, int i, int j) {
45+
int tmp = ar[i];
46+
ar[i] = ar[j];
47+
ar[j] = tmp;
48+
}
49+
50+
public static void main(String[] args) {
51+
QuickSelect quickSelect = new QuickSelect();
52+
int[] array = {-10, 4, 6, 4, 8, -13, 1, 3};
53+
int kthLargestElement = quickSelect.quickSelect(array, 3);
54+
// Prints: 1
55+
System.out.println(kthLargestElement);
56+
}
57+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.williamfiset.algorithms.sorting;
2+
3+
import com.williamfiset.algorithms.utils.TestUtils;
4+
import org.junit.Test;
5+
6+
import java.util.Arrays;
7+
8+
import static com.google.common.truth.Truth.assertThat;
9+
10+
public class QuickSelectTest {
11+
12+
@Test
13+
public void testQuickSelect() {
14+
for (int size = 1; size < 500; size++) {
15+
// Given
16+
QuickSelect quickSelect = new QuickSelect();
17+
int[] values = TestUtils.randomIntegerArray(size, -100, 100);
18+
19+
for (int k = 1; k <= size; k++) {
20+
int[] copy = values.clone();
21+
Arrays.sort(values);
22+
23+
// When
24+
int kthLargestElement = quickSelect.quickSelect(copy, k);
25+
26+
// Then
27+
assertThat(kthLargestElement).isEqualTo(values[k - 1]);
28+
}
29+
}
30+
}
31+
}

0 commit comments

Comments
 (0)