Skip to content

Instantly share code, notes, and snippets.

@osjayaprakash
Last active October 6, 2015 21:07
Show Gist options
  • Save osjayaprakash/3052904 to your computer and use it in GitHub Desktop.
Save osjayaprakash/3052904 to your computer and use it in GitHub Desktop.
Selection Algorithm - Kth Largest / Smallest from unsorted list in O(n)
int A[MAX], N;
int partitions(int low, int high) {
int p=low, r=high, x=A[r], i=p-1;
for (int j=p; j<=r-1; j++) {
if (A[j]<=x){
i=i+1;
swap(A[i],A[j]);
}
}
swap(A[i+1],A[r]);
return i+1;
}
int selection_algorithm(int left, int right, int kth) {
for( ; ; ) {
////Select the Pivot Between Left and Right
int pivotIndex = partitions(left, right);
int len = pivotIndex - left + 1;
if (kth == len)
return A[pivotIndex];
else if (kth < len)
right=pivotIndex-1;
else {
kth=kth-len;
left=pivotIndex+1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment