Skip to content

Instantly share code, notes, and snippets.

@sahid
Created February 17, 2013 23:30
Show Gist options
  • Save sahid/4974098 to your computer and use it in GitHub Desktop.
Save sahid/4974098 to your computer and use it in GitHub Desktop.
Find the kth largest element in an unsorted array.
def findKth(A, k):
if k > len(A) or k < 1:
raise Exception("Invalid Parameters.")
i = 0
while i < k:
imax = i
j = i + 1
while j < len(A):
if A[imax] < A[j]:
imax = j
if imax != i:
A[imax], A[i] = A[i], A[imax]
j += 1
i += 1
return A[-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment