Build a balanced comparison tournament, retaining the record of each value's direct defeats. A record stores a key and a list of records that it directly defeated:There is one key comparison at each merge. Because is a set, all keys are distinct, so the greater winner is unambiguous. Retaining the losing record also retains its own earlier comparison history; it does not merely retain the losing root's value.
tournament(S):
if |S| = 1:
return Node(the element of S, [])
split S into equally sized L and R
a = tournament(L)
b = tournament(R)
if a.key < b.key:
exchange a and b
prepend b to a.losers
return aLet the returned root have value . DefineThe second-largest value can only lose to , so it occurs among those direct losers. This proves the required partition and the exclusion of the second-largest value from the third part. For , the winner participates in exactly merges, so . The other part can be materialized by marking the original element identities in this list and scanning the original inputs, using additional operations without more comparisons between keys.
The balanced comparison tournament usesso . The second-largest search compares direct losers, using comparisons. The record of contains at most direct losers, because loses before becoming the overall winner. Hence the third candidate set has size at most , requiring at most comparisons.
For , the complete comparison count is thereforeThis is and therefore meets the requested bound. The defeat-record lists can be linked in constant local work per merge; flattening the final partition takes work. Thus the method also has linear overall running time under constant-cost key comparisons.
After a balanced comparison tournament, the second-largest element is the maximum among the winner's direct losers. The third-largest must have lost directly to the winner or to that second-largest element: no smaller element could defeat it. Excluding the known top two leaves at most candidates, because the second-largest won at most earlier comparisons. The three stages use at most key comparisons, proving the displayed bound. Defeat records must retain their earlier subtrees; keeping only the overall winner's direct-loser values discards information used by the last stage.