Created
February 9, 2012 02:06
-
-
Save andlima/1776496 to your computer and use it in GitHub Desktop.
Quick selection algorithm
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
int quick_find_kth(int *v, int n, int k) { | |
if (n == 1 && k == 0) return v[0]; | |
int pivot = v[n-1]; | |
int store = 0; | |
for (int i=0; i<n-1; i++) { | |
if (v[i] < pivot) { | |
swap(v[i], v[store++]); | |
} | |
} | |
swap(v[store], v[n-1]); | |
if (store == k) { | |
return pivot; | |
} else if (store > k) { | |
return quick_find_kth(v, store, k); | |
} else { | |
return quick_find_kth(v+store+1, n-store-1, k-store-1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment