The go language uses a heap sort method to sort 10 million int random numbers.

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
The previous article used the Quicksort method to sort, but if the rapid sorting method for high repetition rate of slice, time complexity will soar, the speed is quite slow, so try to heap sorting, experimental results, feel very good. Here is the code, you can refer to, This is the building of the big top pile. Two fork tree features: Last Non-leaf node: root = LENGTH/2 (root down rounding when length is odd) in the Go Language index position: root-1, left and right child node: child_l = 2*root, cable Lead position: Child_l-1, right Child's node: 2*root+1 index location. Package Mainimport ("FMT" "Math/rand") func main () {Num: = 10000000var list []intfor I: = Num; i > 0; i--{list = append (list, Rand. INTN (10000)}//Generate 10 million random numbers of 0---10000. Length: = Len (list) for root: = LENGTH/2-1; Root >= 0; root--{sort (list, root, Length)}//First build large top heap for I: = length-1; I >= 1; i--{list[0], list[i] = List[i], list[0]sort (list, 0, I)}//Adjust the position and build and build the heap from the first root. If you don't understand why, it should be clear that the FMT should be made more than once.  PRINTLN (list)}func sort (list []int, root, length int) {for {child: = 2*root + 1 if child >= length {break} if child+1 < length && List[child] < list[child+1] {child++//The focus here is that the heap may also need to be adjusted to the left and right of the child as the node is adjusted}if List[root] > L Ist[child] {Return}list[root], list[child] = List[child], list[root]root = Child}}
Related Article

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.