[Golang] Data Structure-Tree selection sort (Tournament sort)

Source: Internet
Author: User
Tags pow

Click the above simple sorting
Simple selection of sorting is easy to understand, and the code is easy to implement. But after all, the number of comparisons is too many. This problem is improved by the tree selection sort.

Principle
In simple terms, the tree selection sort is the smallest of the elements that are slightly larger in comparison to the minimum value, after selecting a round to find the minimum. This avoids the simple choice to query the kind, discard the previously compared results, each time all re-compare the situation.

Process examples

    • First list all the elements to be sorted, such as: 8, 4, 12, 7, 35, 9, 22, and use them to form a leaf element full of two fork trees, the insufficient position with ∞ as a supplement.
      The two-phase comparison of the elements, respectively, to obtain a smaller value: 4,7,9,22. Again 22 comparisons, get 4, 9. The final comparison gets the minimum value 4 at a time. The result is a complete two-fork tree:

    • After the completion of a comparison, the winner 4 of the leaf node is changed to ∞, and then by its sibling node 8 continue to participate in the next round of comparisons. From this point on, element 8 only needs to be compared with the other winning non-parent nodes just by building the tree structure, for example, only in comparison with 7,9, we can get the minimum element is 7

    • Then the leaf node of element 7 is changed to ∞, the sibling node 12 and 8, 9 nodes, you can get 8:

    • And so on, finally get the last element 35:

Complexity of Time
Because each time only needs to compare with the other winning nodes, the time complexity is reduced to O (n^2) compared to the simple selection sort O (Nlogn).
However, because the data of each winning node is stored, more storage space is needed, and the comparison behavior of n-1 and ∞ is more redundant.

Code implementation

Package Mainimport ("FMT" "math")//declares a struct of a node, contains the node value size and whether it is necessary to participate in the comparison of type node struct {//numeric size value int//leaf Node status available bool//medium sorting, convenient failure rank Int}func main () {var length = ten var mm = make (Map[int]int, length var o []int//First prepare a sequential random number (Qie) group (Pian) for I: = 0; i < length; i++ {Mm[i] = i} for K, _: = range mm {o = append (o, k)} FMT. Println (o) treeselectionsort (o)}func Treeselectionsort (Origin []int) []int {//The number of layers in the tree var level int var result  = Make ([]int, 0, Len (origin)) for POW (2, level) < Len (origin) {level++}//leaf node var leaf = Pow (2, level) var tree = make ([]node, leaf*2-1)//fill in the data for the leaf node first for i: = 0; I < Len (origin); i++ {tree[leaf+i-1] = Node{origin[i], true, I}}//Each layer compares the leaf sibling size and selects a larger value as parent node for i: = 0; I < level;         i++ {//Current layer node number nodecount: = POW (2, level-i)//Sibling comparison for J: = 0; j < NODECOUNT/2;   Compareandup (&tree, Nodecount-1+j*2)}}//This time the top of the tree is the smallest element of result = Append (result, tree[0].value) Fmt. PRINTLN (Result)//After selecting the smallest element, there is still n-1 to sort for t: = 0; T < Len (origin)-1; t++ {//Win node Winnode: = Tree[0].rank + leaf-1//Change the leaf node status of the winning ball to fail tree[winnode].available = False//Starting with the next round, simply compare the sibling nodes of each winning node for I: = 0; I < level;            i + + {leftnode: = Winnode if winnode%2 = = 0 {leftnode = winNode-1}        Compare sibling-to-node size and pass the winning node up Compareandup (&tree, leftnode) Winnode = (leftNode-1)/2 }//Each round will be the smallest push to the top of the tree result = Append (result, Tree[0].value) fmt. PRINTLN (Result)} return Origin}func Compareandup (tree *[]node, Leftnode int) {rightnode: = Leftnode + 1//except The non-left node is invalid or the right node is valid and larger than the left node, otherwise there is no left node if! (*tree) [Leftnode].available | | (*tree) [rightnode].available && (*tree) [Leftnode].value >(*tree) [Rightnode].value) {(*tree) [(leftNode-1)/2] = (*tree) [Rightnode]} else {(*tree) [(leftNode-1)/2] = (*tr EE) [Leftnode]}}func pow (x, y int) int {return int (math. Pow (float64 (x), float64 (y)))}

Run results

[Golang] Data Structure-Tree selection sort (Tournament sort)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.