Golang Minimum heap sorting implementation

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The project has a module to a large number of tasks need to control timeout, the internal implementation of a timer component, the bottom is based on the minimum heap algorithm and time wheel. The minimum heap algorithm is quite simple, a complete binary tree, each non-leaf node is smaller than its two sub-nodes, this is a minimum heap.

This article is still in the continuous update changes, please go to the original address http://dmwan.cc

The implementation code is as follows:

package mainimport (    "fmt")func heapSort(input []int){    inputLen := len(input)    if inputLen == 0 {        return    }    for i:=0; i<inputLen; i++{        minAjust(input[i:])    }}func minAjust(input []int){    inputLen := len(input)    if inputLen <= 1{        return    }    for i:= inputLen/2 -1; i>=0; i--{        if (2*i+1 <= inputLen-1) && (input[i] >= input[2*i+1]){           input[i], input[2*i+1] = input[2*i+1], input[i]        }        if (2*i+2<= inputLen-1) && (input[i] >= input[2*i+2]){            input[i], input[2*i+2] = input[2*i+2], input[i]        }    }}func main (){    testSlice := []int {2,3,1,4,5,6,2,1,23,43,1,32,3,5,2,1,8,54,4,0}    fmt.Println(testSlice)    heapSort(testSlice)    fmt.Println(testSlice)}

Meet Formula A[i]<a[2*i+1] &&a[i]<a[2*i+2] can, this if can't think of, draw drawing is OK.

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.