Contents
Tournament sort
Tournament sort is a sorting algorithm. It improves upon the naive selection sort by using a priority queue to find the next element in the sort. In the naive selection sort, it takes O(n) operations to select the next element of n elements; in a tournament sort, it takes O(log n) operations (after building the initial tournament in O(n)). Tournament sort is a variation of heapsort.
Common application
Tournament replacement selection sorts are used to gather the initial runs for external sorting algorithms. Conceptually, an external file is read and its elements are pushed into the priority queue until the queue is full. Then the minimum element is pulled from the queue and written as part of the first run. The next input element is read and pushed into the queue, and the min is selected again and added to the run. There's a small trick that if the new element being pushed into the queue is less than the last element added to the run, then the element's sort value is increased so it will be part of the next run. On average, a run will be 100% longer than the capacity of the priority queue. Tournament sorts may also be used in N-way merges.
Etymology
The name comes from its similarity to a single-elimination tournament where there are many players (or teams) that play in two-sided matches. Each match compares the players, and the winning player is promoted to play a match at the next level up. The hierarchy continues until the final match determines the ultimate winner. The tournament determines the best player, but the player who was beaten in the final match may not be the second best – he may be inferior to other players the winner bested.
Sorting scheme
Sort numbers 72356014 (count = 8) 7_ __ __ \2_ __ __ 7_ 7_ __ 2_/ \ / \ / \ \ \ \ 3 2- __ 2- __ 2- __ 3- 5- 5- 7- \3/ \ _/ \ _/ \ \3/ \ 5/ \ / \ \ 5/ \ / \ / \ / \ \ \ \ _0 _1 _2 _3 _4 _5 _67 6 / / / / / / / \0 / 6 / 6 / __ / __ / / / 0/ \ / \ / \ / \ / \ / / / 1 0- __ 1- 4- 4- 4- 6- 6- \1/ \1_/ 4_/ __/ _/ 4/ __/ Compares: 7 + 2 + 2 + 2 + 2 + 1 + 1 = 17
On
Onminmax(n log n) = (ln(n) / ln(2) - 1) * n + 1 On = (n - 1) + (n / 2) * (n / 4) + (n / (2 * 2) ) * (n / ( 4 * 2 )) + (n / (2 * 2 * 2) ) * (n / ( 4 * 2 * 2 )) + ... O8 = (8 - 1) + (8 / 2) * (8 / 4) + (8 / (2 * 2) ) * (8 / ( 4 * 2 )) O8 = 7 + 4 * 2 + 2 * 1 = 7 + 8 + 2 = 17
Implementations
Haskell
The following is an implementation of tournament sort in Haskell, based on Scheme code by Stepanov and Kershenbaum.
Javascript
This article is derived from Wikipedia and licensed under CC BY-SA 4.0. View the original article.
Wikipedia® is a registered trademark of the
Wikimedia Foundation, Inc.
Bliptext is not
affiliated with or endorsed by Wikipedia or the
Wikimedia Foundation.