Skip to content

Instantly share code, notes, and snippets.

@boulethao
Last active July 9, 2018 18:21
Show Gist options
  • Save boulethao/a23932ed5c6572fb64ce04bc30e27448 to your computer and use it in GitHub Desktop.
Save boulethao/a23932ed5c6572fb64ce04bc30e27448 to your computer and use it in GitHub Desktop.
Find the element of rank k using qsort type algorithm
def find_kth_element(a, lo, hi, k):
if lo >= hi:
return a[lo]
p = partition(a, lo, hi)
if (k-1) == p:
return a[p]
if (k - 1) < p:
return find_kth_element(a, lo, p-1, k)
if (k + 1) > p:
return find_kth_element(a, p+1, hi, k)
def partition(a, lo, hi):
pivot = a[hi]
i = lo
j = lo
while j <= hi:
if (a[j] < pivot):
a[i], a[j] = a[j], a[i]
i += 1
j += 1
a[i], a[hi] = a[hi], a[i]
return i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment