Skip to content

Instantly share code, notes, and snippets.

@incfly
Last active August 29, 2015 14:05
Show Gist options
  • Save incfly/718ee37988ee520b5b8e to your computer and use it in GitHub Desktop.
Save incfly/718ee37988ee520b5b8e to your computer and use it in GitHub Desktop.
#define _cp(a,b) ((a)<(b))
//k+1's element. jilin's template
int kth_element(int n, int a[], int k){
int l = 0, r = n-1, i, j, key;
while (l < r){
for (i=l-1, j = r+1, key = a[(i+j)>>1]; i < j; ){
// j--, i++ at beginning of the loop is because, if i < j but a[i] == a[j] == key
// then not progress any more. i, j points to end of range that is done.
for (j--; _cp(key, a[j]); j--);
for (i++; _cp(a[i], key); i++);
if (i < j) swap(a[i], a[j]);
}
if (k > j) l = j+1;
else r = j;
}
return a[k];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment