in Algorithms
348 views
3 votes
3 votes
Selection of the kth smallest element in a set of n elements.

O(n)

O(n^2).

Reason.
in Algorithms
348 views

1 Answer

0 votes
0 votes

(Use Min Heap)

1) Build a Min Heap MH of the first k elements (arr[0] to arr[k-1]) of the given array. O(k)

2) For each element, after the kth element (arr[k] to arr[n-1]), compare it with root of MH.
……a) If the element is greater than the root then make it root and call heapify for MH
……b) Else ignore it.
// The step 2 is O((n-k)*logk)

3) Finally, MH has k largest elements and root of the MH is the kth largest element.

Time Complexity: O(k + (n-k)Logk) without sorted output. If sorted output is needed then O(k + (n-k)Logk + kLogk)

Related questions

0 votes
0 votes
1 answer
4