Given n numbers, how do I find the largest and second largest number using at most n+log(n) comparisons?
Note that it\'s not O(n+log(n)), but really n+log(n) compari
Is there a problem with this? It's at most 3n comparisons (not counting the i < n
comparison). If you count that, it's 4n (or 5n in the second example).
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];
}
}
another way to code it:
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];