Last active
July 14, 2018 20:12
-
-
Save ENAML/7a29d8a1cab971c92d8f8f6845e93c5d to your computer and use it in GitHub Desktop.
QuickSelect algo implementation in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class QuickSelect { | |
// STATIC VARS | |
static Random rand = new Random(); | |
/* | |
Tests | |
----- | |
*/ | |
public static void main(String[] args) { | |
int[] testArr = new int[9]; | |
System.out.println("TESTING _WITHOUT_ DUPLICATES"); | |
for (int i = 0; i < testArr.length; i++) | |
testArr[i] = i; | |
for (int i = 0; i < testArr.length; i++) { | |
shuffle(testArr); | |
test(testArr, i); | |
} | |
System.out.println("\n\n"); | |
System.out.println("TESTING _WITH_ DUPLICATES"); | |
for (int i = 0; i < testArr.length; i++) | |
testArr[i] = i / 2; | |
for (int i = 0; i < testArr.length; i++) { | |
shuffle(testArr); | |
test(testArr, i); | |
} | |
} | |
public static void test(int[] arr, int k) { | |
System.out.println("arr: " + Arrays.toString(arr) + " | k: " + k); | |
System.out.println(" -> kth elt: " + quickSelect(arr, k) ); | |
} | |
/* | |
QuickSelect Algo | |
---------------- | |
- k \in [0, arr.length) | |
*/ | |
public static int quickSelect(int[] arr, int k) { | |
return quickSelect(arr, 0, arr.length - 1, k); | |
} | |
public static int quickSelect(int[] arr, int lo, int hi, int k) { | |
int pivotIdx = getPivot(arr, lo, hi); | |
int partitionIdx = partition(arr, lo, hi, pivotIdx); | |
if (partitionIdx > k) { | |
return quickSelect(arr, lo, partitionIdx - 1, k); | |
} | |
else if (partitionIdx < k) { | |
return quickSelect(arr, partitionIdx + 1, hi, k); | |
} | |
return arr[partitionIdx]; | |
} | |
public static int partition(int[] arr, int lo, int hi, int pivotIdx) { | |
int pivotVal = arr[pivotIdx]; | |
swap(arr, hi, pivotIdx); | |
int partitionIdx = lo; | |
for (int i = lo; i <= hi - 1; i++) { | |
if (arr[i] < pivotVal) { | |
swap(arr, partitionIdx, i); | |
partitionIdx++; | |
} | |
} | |
swap(arr, hi, partitionIdx); | |
return partitionIdx; | |
} | |
public static int getPivot(int[] arr, int lo, int hi) { | |
return rand.nextInt(hi + 1 - lo) + lo; | |
} | |
public static void swap(int[] arr, int i, int j) { | |
int tmp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = tmp; | |
} | |
/** | |
fischer-yates shuffle | |
--------------------- | |
*/ | |
static void shuffle(int[] arr) { | |
int len = arr.length; | |
for (int i = 0; i < len; i++) { | |
int j = rand_range(i, len); | |
swap(arr, i, j); | |
} | |
} | |
static int rand_range(int lo, int hi) { | |
return rand.nextInt(hi - lo) + lo; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment