Possible Duplicate:
Find the 2nd largest element in an array with minimum # of comparisom
May I know how to achieve searching the biggest and second biggest number in O(n+logn) time? Thank you in advance.
Best regards, Pidig
Possible Duplicate:
Find the 2nd largest element in an array with minimum # of comparisom
May I know how to achieve searching the biggest and second biggest number in O(n+logn) time? Thank you in advance.
Best regards, Pidig
Note that O(n+logn) = O(n)
, and iterating twice on the list is O(n)
.
Because it iterate constant number of times on the array, the algorithm is O(n)
.
For general purpose k
largest elements: You can do it using a min heap in O(nlogk)
, or selection algorithm in O(n)
- as described in this answer, but for 2 greatest elements - these methods are overkill.
I guess you mean n + log(n) - 2 comparisons.
Here is how you do it.
Compare elements in groups of two. i.e. make n/2 groups of two elements each.
Continue in this way with n/4, n/8, n/16 and so on till you get the first(largest) element.
Now the next largest element has to be amongst the losers of the first element in this method. Hence log(n) more comparisons for this.
Precisely this will take n + log(n) - 2 comparisons.