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

你可能感兴趣的:(golang,数据结构,算法)