
Algorithm to return kth largest number
By:
indushree-kumar on
Jul 24th, 2012 | syntax:
None | size: 0.71 KB | hits: 14 | expires: Never
kthLargest(A, k)
let r be a random number in the range 1 to length(A)
let num = A[r]
let A1, A2 be new arrays
/*split the given numbers into a array A1 of small numbers and A2 of big numbers*/
for i = 1 to n
if A[i] < k then
append A[i] to A1
else if A[i] > k then
append A[i] to A2
end for
if k <= length(A1):
/*it's in the pile of small elements*/
return kthLargest(A1, k) /*recursively call kthLargest*/
else if k > length(A) - length(A2)
/*it's in the pile of big elements*/
return kthLargest(A2, k - (length(A) - length(A2)) /*recursively call kthLargest*/
else
/*it's equal to the num*/
return num
The complexity of this algorithm is O(n).