Trying to take this literally: Can anyone know how to make algorithm2 faster than the easiest method?
and // You need focus on algo2 function.
, with algorithm2 finding the runner-up among the champion's opponents in a tournament.
The
The straightforward way to find the k
-max values of an unordered collection is to feed a priority queue of size k
with its elements.
The
The cases with k
<= 2 are special in not warranting an explicit priority queue: after initialisinginitializing k
candidates from the first k
elements, just compare each of the remaining elements to the current k
-max candidate. If the current element is greater: if looking for the top two elements, compare to the max candidate: if greater, keep that value as the new runner-up and make the current element the max candidate, else just replace the runner-up.
This
This requires kN+O(1)\$kN+O(1)\$ assignments, worst case, and kN-O(1)\$kN-O(1)\$ comparisons.
The
The tournament approach to 2-max requires N+ld(N)-O(1)\$N+ld(N)-O(1)\$ comparisons and N+O(ld(N))\$N+O(ld(N))\$ assignments.
According
According to this, algorithm2 may use slightly more than half the comparisons and assignments algorithm1 does. Then again, for "random input", I'd expect the number of assignments in the simplistic approach to grow in the ballpark of c*lg(N)\$c*lg(N)\$ to c*sqrt(N)\$c*sqrt(N)\$ - strictly lower than N/2\$N/2\$ for "non-trivial" values of N\$N\$.
For
For any contemporary sequential machine implementation, I'd expect simplistic to win hands down against tournament. Design, test, analysis and measurement of parallel renditions left as an exercise…