Originally posted by: Armitage
Originally posted by: Armitage
Let's say you need the greatest m values
Copy the first m elements into your max array.
Sort it (O(mlogm)).
Now iterate from m->n
If the element is > the smallest element in the max array, insert it into the max array dropping the smallest member.
You will have to do this insertion at most (n-m) times, and the maximum number of comparisons you need to do to make the insertion is m-1 times, so the maximum number of comparisons you need to do is m*(n-m).
So the overall O for the worst case (original array already sorted and starting from the wrong end) would be O(mlogm) + O(nm-m^2)
For the best case (array already sorted, starting from the right end), you would never do any insertions ... just n-m comparisons.
I suspect my lack of formal compsci may be showing here, but it should be something like that.
Heh ... for the case of n=1,000,000, m=10 the second term here works out to 9,999,900 while nlogn comes to 6,000,000
So you're still better off sorting in the worst case, although I suspect in a random case this algorithm would do better.
nlogn does mean base 10 logarithm right?