Created
February 17, 2013 23:30
-
-
Save sahid/4974098 to your computer and use it in GitHub Desktop.
Find the kth largest element in an unsorted array.
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
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