Go语言用堆排序的方法进行一千万个int随机数排序.

前端之家收集整理的这篇文章主要介绍了Go语言用堆排序的方法进行一千万个int随机数排序.前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. 上篇文章用的是quicksort方法排序,但是如果用快速排序法对重复率很高的slice排序的时候,时间复杂度会激增,速度相当慢
  2. 所以尝试了一下堆排序,实验结果,感觉挺好的.下面是代码,大家可以参考一下,这个是建立的大顶堆.
  3. 二叉树的特性:
  4. 最后一个非叶子节点 root = length/2(当length为奇数的时候root向下取整) GO语言中的索引位置:root - 1,左右孩子节点:child_l = 2*root,索引位置:child_l-1,右孩子的节点: 2*root+1 索引位置.
  5.  
  6. package main
  7.  
  8. import (
  9. "fmt"
  10. "math/rand"
  11. )
  12.  
  13. func main() {
  14. Num := 10000000
  15. var list []int
  16. for i := Num; i > 0; i-- {
  17. list = append(list,rand.Intn(10000))
  18. } //生成一千万个0---10000的随机数.
  19. length := len(list)
  20. for root := length/2 - 1; root >= 0; root-- {
  21. sort(list,root,length)
  22. } //第一次建立大顶堆
  23. for i := length - 1; i >= 1; i-- {
  24. list[0],list[i] = list[i],list[0]
  25. sort(list,i)
  26. } //调整位置并建并从第一个root开始建堆.如果不明白为什么,大家多把图画几遍就应该明朗了
  27. fmt.Println(list)
  28. }
  29. func sort(list []int,length int) {
  30. for {
  31. child := 2*root + 1
  32. if child >= length {
  33. break
  34. }
  35. if child+1 < length && list[child] < list[child+1] {
  36. child++ //这里重点讲一下,就是调整堆的时候,以左右孩子为节点的堆可能也需要调整
  37. }
  38. if list[root] > list[child] {
  39. return
  40. }
  41. list[root],list[child] = list[child],list[root]
  42. root = child
  43. }
  44. }
  45.  
  46.  

猜你在找的Go相关文章