Search for the largest and second largest of N numbers

Given n numbers, how to find the largest and second largest number using at most n + log (n) comparisons?

Note that this is not O (n + log (n)), but really n + log (n) comparisons.

+5
source share
2 answers

pajton gave a comment.

Let me clarify.

As Python said, this can be done by choosing a tournament.

Think of it as a nightly single-player tennis tournament, where the player’s abilities are in strict order, and the result of the match is determined solely by this order.

. .. ( ).

.

.

node node.

- . ..

n .

. , . log n. .

n-1 ( ), logn -1.

, n + logn - 2.

, , . .

, , . 1 .

n .

, , , . , , log n , .

+10

? 3n ( i < n). , 4n ( 5n ).

double first = -1e300, second = -1e300;
for (i = 0; i < n; i++){
  if (a[i] > first){
    second = first;
    first = a[i];
  }
  else if (a[i] > second && a[i] < first){
    second = a[i];
  }
}

:

for (i = 0; i < n; i++) if (a[i] > first) first = a[i];
for (i = 0; i < n; i++) if (a[i] < first && a[i] > second) second = a[i];
+1

All Articles