n*log(3)n排序算法

前端之家收集整理的这篇文章主要介绍了n*log(3)n排序算法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

老规矩,上来先表示对原作者的敬重之心:n*log(3)n排序算法 -- 修江的芦苇


关于三叉堆排序呢,对于已经理解了二叉堆排序的人来说,其实很容易理解。该讲的在原作里面,作者已经讲的很清楚了,这里就只贴一下代码了。


首先是 heap.go:

  1. package heap // import "triple-heap"
  2.  
  3. import "sort"
  4.  
  5. type Interface interface {
  6. sort.Interface
  7. Push(x interface{})
  8. Pop() interface{}
  9. }
  10.  
  11. func Init(h Interface) {
  12. n := h.Len()
  13. for i := n/3 - 1; i >= 0; i-- {
  14. down(h,i,n)
  15. }
  16. }
  17.  
  18. func Push(h Interface,x interface{}) {
  19. h.Push(x)
  20. up(h,h.Len()-1)
  21. }
  22.  
  23. func Pop(h Interface) interface{} {
  24. n := h.Len() - 1
  25. h.Swap(0,n)
  26. down(h,n)
  27. return h.Pop()
  28. }
  29.  
  30. func Remove(h Interface,i int) interface{} {
  31. n := h.Len() - 1
  32. if n != i {
  33. h.Swap(i,n)
  34. down(h,n)
  35. up(h,i)
  36. }
  37. return h.Pop()
  38. }
  39.  
  40. func Fix(h Interface,i int) {
  41. down(h,h.Len())
  42. up(h,i)
  43. }
  44.  
  45. func up(h Interface,j int) {
  46. for {
  47. i := (j - 1) / 3 // parent
  48. if i == j || !h.Less(j,i) {
  49. break
  50. }
  51. h.Swap(i,j)
  52. j = i
  53. }
  54. }
  55.  
  56. func down(h Interface,n int) {
  57. for {
  58. j1 := 3*i + 1
  59. if j1 >= n || j1 < 0 { // j1 < 0 after int overflow
  60. break
  61. }
  62. j := j1 // left child
  63. if j2 := j1 + 1; j2 < n && !h.Less(j,j2) {
  64. j = j2 // = 3*i + 2 // mid child
  65. }
  66. if j3 := j1 + 2; j3 < n && !h.Less(j,j3) {
  67. j = j3 // = 3*i + 3 // right child
  68. }
  69. if !h.Less(j,j)
  70. i = j
  71. }
  72. }


接下来是 sort.go:

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "triple-heap"
  6. )
  7.  
  8. type myHeap []int
  9.  
  10. func (h *myHeap) Less(i,j int) bool {
  11. return (*h)[i] < (*h)[j]
  12. }
  13.  
  14. func (h *myHeap) Swap(i,j int) {
  15. (*h)[i],(*h)[j] = (*h)[j],(*h)[i]
  16. }
  17.  
  18. func (h *myHeap) Len() int {
  19. return len(*h)
  20. }
  21.  
  22. func (h *myHeap) Pop() (v interface{}) {
  23. *h,v = (*h)[:h.Len()-1],(*h)[h.Len()-1]
  24. return
  25. }
  26.  
  27. func (h *myHeap) Push(v interface{}) {
  28. *h = append(*h,v.(int))
  29. }
  30.  
  31. func TripleHeapSort(h heap.Interface) {
  32. heap.Init(h)
  33. var t = make([]interface{},h.Len())
  34. for h.Len() > 0 {
  35. t = append(t,heap.Pop(h))
  36. }
  37. for i := 0; i < len(t); i++ {
  38. h.Push(t[i])
  39. }
  40. }
  41.  
  42. func main() {
  43. var h = myHeap{5,3,1,9,6,4,7,8,2}
  44. fmt.Println(h)
  45. TripleHeapSort(&h)
  46. fmt.Println(h)
  47. }



运行 go run sort.go结果:

[5 3 1 9 0 6 4 7 8 2]
[0 1 2 3 4 5 6 7 8 9]


对于包的组织和管理,大家自己去搞咯~

好啦,本期节目到此为止,咱们下期再见!

猜你在找的Go相关文章