Golang 数据结构与算法 —— 堆排序

目录结构

  • bucketSort
    – bucketSort.go
    – bucketSort_test.go
bucketSort.go
package heapSort 

// 函数入口
func HeapSort(s []int) {
	// 先造堆,再排序
	arrToHeap(s)
	sort(s)
}

// 造大顶堆
func arrToHeap(s []int) {
	for i := len(s) - 1; i > 0; i-- {
		if s[i] > s[i/2] { // 子结点比父结点大,则交换
			swap(s, i, i/2)
		}
	}
}

// 堆排序
func sort(s []int) {
	for i := len(s) - 1; i > 0; i-- {
		sort2.Swap(s, i, 0)
		arrToHeap(s[:i])
	}
}

// 交换
func swap(s []int, i, j int) {
	s[i], s[j] = s[j], s[i]
}

bucketSort_test.go
package heapSort

import (
	"fmt"
	"math/rand"
	"testing"
)

func BenchmarkHeapSort(b *testing.B) {
	s := make([]int, 0)
	for j := 0; j < 50; j++ {
		j := rand.Intn(1000)
		s = append(s, j)
	}
	b.StartTimer()
	for i := 0; i < b.N; i++ {
		HeapSort(s)
	}
	b.StopTimer()
}

测试结果
BenchmarkHeapSort
BenchmarkHeapSort-12    	  972006	      1168 ns/op
PASS
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值