Since we only care about the execution time of COMPARE()
, the solution is to call COMPARE()
as less as possible, yet achieving our goal, which is targeting and sorting the first k
largest numbers in a given set of n
numbers
- Iterate through
n
numbers:i_1
,i_2
,...,i_n
- Compare them with the smallest number
k_smallest
in firstk
numbers - If
i
is larger thank_smallest
, use binary search to find the best position ink
fori
, then push all numbers ink
that are smaller thani
one position forward, so that there will be a empty space fori
to insert into. - Else if
i
is smallerk_smallest
, skip it - Repeat steps above until all
n
numbers are examined.
From the steps we see above, only step 2 and 3 are required to use COMPARE()
, therefore, we manage to dramatically reduce our calling times for COMPARE()
and successfully complete our comparing tasks.