0

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

Community
  • 1
  • 1
pidig89
  • 169
  • 1
  • 11

3 Answers3

7

Note that O(n+logn) = O(n), and iterating twice on the list is O(n).

  1. Iterate once to find the max and remove/mark it,
  2. Then iterating the second time to find the new max (second biggest element),

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.

Community
  • 1
  • 1
amit
  • 175,853
  • 27
  • 231
  • 333
3

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.

sukunrt
  • 1,523
  • 10
  • 20
1

You can actually do that in O(n) time: Selection Algorithm

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118