n*log(3)n排序算法
来源:互联网 发布:扩展欧几里得算法公式 编辑:程序博客网 时间:2024/04/28 00:51
老规矩,上来先表示对原作者的敬重之心:n*log(3)n排序算法 -- 修江的芦苇
关于三叉堆排序呢,对于已经理解了二叉堆排序的人来说,其实很容易理解。该讲的在原作里面,作者已经讲的很清楚了,这里就只贴一下代码了。
首先是 heap.go:
package heap // import "triple-heap"import "sort"type Interface interface {sort.InterfacePush(x interface{})Pop() interface{}}func Init(h Interface) {n := h.Len()for i := n/3 - 1; i >= 0; i-- {down(h, i, n)}}func Push(h Interface, x interface{}) {h.Push(x)up(h, h.Len()-1)}func Pop(h Interface) interface{} {n := h.Len() - 1h.Swap(0, n)down(h, 0, n)return h.Pop()}func Remove(h Interface, i int) interface{} {n := h.Len() - 1if n != i {h.Swap(i, n)down(h, i, n)up(h, i)}return h.Pop()}func Fix(h Interface, i int) {down(h, i, h.Len())up(h, i)}func up(h Interface, j int) {for {i := (j - 1) / 3 // parentif i == j || !h.Less(j, i) {break}h.Swap(i, j)j = i}}func down(h Interface, i, n int) {for {j1 := 3*i + 1if j1 >= n || j1 < 0 { // j1 < 0 after int overflowbreak}j := j1 // left childif j2 := j1 + 1; j2 < n && !h.Less(j, j2) {j = j2 // = 3*i + 2 // mid child}if j3 := j1 + 2; j3 < n && !h.Less(j, j3) {j = j3 // = 3*i + 3 // right child}if !h.Less(j, i) {break}h.Swap(i, j)i = j}}
接下来是 sort.go:
package mainimport ("fmt""triple-heap")type myHeap []intfunc (h *myHeap) Less(i, j int) bool {return (*h)[i] < (*h)[j]}func (h *myHeap) Swap(i, j int) {(*h)[i], (*h)[j] = (*h)[j], (*h)[i]}func (h *myHeap) Len() int {return len(*h)}func (h *myHeap) Pop() (v interface{}) {*h, v = (*h)[:h.Len()-1], (*h)[h.Len()-1]return}func (h *myHeap) Push(v interface{}) {*h = append(*h, v.(int))}func TripleHeapSort(h heap.Interface) {heap.Init(h)var t = make([]interface{}, 0, h.Len())for h.Len() > 0 {t = append(t, heap.Pop(h))}for i := 0; i < len(t); i++ {h.Push(t[i])}}func main() {var h = myHeap{5, 3, 1, 9, 0, 6, 4, 7, 8, 2}fmt.Println(h)TripleHeapSort(&h)fmt.Println(h)}
运行 go run sort.go结果:
[5 3 1 9 0 6 4 7 8 2]
[0 1 2 3 4 5 6 7 8 9]
对于包的组织和管理,大家自己去搞咯~
好啦,本期节目到此为止,咱们下期再见!
0 0
- n*log(3)n排序算法 初稿
- n*log(3)n排序算法
- 3sum ~ 2log(N)算法
- 算法常用的时间复杂度(log(n),sqrt(x),n,n*log(n),n^2,n^3,2^n)的函数坐标图
- n*n基础排序算法
- Fibonacci数列第n项的log(n)算法
- 高效求幂取余 算法,复杂度 log(n)
- O(n^2)排序算法
- 排序算法-n^2级别
- 排序算法-插入排序 Insertion Sort Θ(n-n)
- 直接插入排序算法。(时间复杂度n*n)
- log(n!) = Θ(n·log(n))
- git log -n 1
- 计算log(N!)
- 排序算法达快不到O(n)
- 一个时间效率为n的排序算法
- 算法复习之:N^2排序
- 二维数组排序 n种算法
- web之瀑布流布局
- 【比较】StringBuffer类和String
- ORACLE 常用函数及日期控制
- Java 基础——类的加载
- leetcode 15. 3Sum
- n*log(3)n排序算法
- PAT-B 1053. 住房空置率
- 客户端网页编程1
- Java枚举类
- python运维之IPY模块
- Java 基础——数组解析
- 学习react-native之Navigator
- 客户端网页编程2
- eclipse使用debug模式启动不起来