How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?
The best time you can expect is linear, since you have to at least look through all the elements.
Here is my pseudocode to solve the problem:
//assume list has at least 2 elements
(max, nextMax) = if (list[0] > list[1])
then (list[0], list[1])
else (list[1], list[0])
for (2 <= i < length) {
(max, nextMax) = if (max < list[i]) => (list[i], max)
elseif (nextMax < list[i]) => (max, list[i])
else (no change) => (max, nextMax)
}
return (max, nextMax)