Friday, May 21, 2010

k largest elements in an array

given an array of numbers, write a program to return the k largest numbers.
For eg: if the array of numbers is 2,9,6,4,3,8,56,39,5 and k=3 then return 56,39,9.



This can be solved in myriad ways.

1). if k is really small then one can use selection sort.

2) A variant of a quick sort can also be used for this problem.

3) construct min heap with k elements and then remove minimum element and insert an element from remaining array elements. After this process the larges elements will be left over in a heap.

No comments:

Post a Comment