Wednesday, June 26, 2013

Data Structure Problem 1 :
Select Max k elements from a given array of n elements :

This problem can be done in 5 different types of algorithmic time runs.
1. O(nxn)

2. nk

Simply scan the array for each element and compare with other elements.
3. O(nlogn)

sort the array and select first k elements.

4. O(nlogk)

create a min heap and insert first k elements in to it. Now for each next element compare the getMin() of heap. If this getMin() is less than the element being compared. replace getMin() element with the new element, else disregard new element. In the end we will have a heap of k max elements form the array.

5. The solution number 4 can further be improved by using the heapifying an array method. which takes O(n) time.

I have not posted the code for readers to give it a try themselves. If you nee pseudocode or code for any of the above solution let me know. I will try to get back to you when time allows. 

No comments:

Post a Comment