package heap
import (
"fmt"
"testing"
)
func TestHeapSort(t *testing.T) {
arr := []int{ 1,22,3,44,5,66,7,88 }
heapSort(arr)
fmt.Println(arr)
}
func heapInsert(arr []int, index int) {
for arr[index] > arr[(index - 1) /2] { // < or >
swap(arr, index, (index - 1) /2 )
index = (index - 1) / 2
}
}
func heapify(arr []int,index,heapSize int) {
leftChild := 2 * index + 1
for leftChild < heapSize {
largest := leftChild
if leftChild + 1 < heapSize && arr[leftChild] < arr[leftChild + 1] { // arr[leftChild] < arr[leftChild + 1] or arr[leftChild] > arr[leftChild + 1]
largest = leftChild + 1
}
if arr[largest] <= arr[index] { // <= or >
break
}
swap(arr, index, largest)
index = largest
leftChild = 2 * index + 1
}
}
func heapSort(arr []int) {
if arr == nil || len(arr) < 2 {
return
}
// O(N*logN)
//for i := 0; i < len(arr); i++ { // O(N)
// heapInsert(arr,i) // O(logN)
//}
for i := len(arr) -1; i >= 0; i-- { //O(N) 算法 不要求数组有序 ,只要求大根堆的话,该方法非常Nice,适用于批量的,数组无序的情况
heapify(arr,i,len(arr))
}
heapSize := len(arr)
heapSize--
swap(arr,0,heapSize)
for heapSize > 0 { // O(N)
heapify(arr,0,heapSize) // O(logN)
heapSize--
swap(arr,0,heapSize) // O(1)
}
}
func swap(arr []int, i, j int) {
arr[i], arr[j] = arr[j],arr[i]
}
排序——堆排序
于 2021-10-23 23:08:30 首次发布