Heapsort Build And Extract Max (Go)
Sort a Go slice by building a max heap in place then repeatedly extracting the maximum to the end.
Code
package main
func heapsort(arr []int) {
n := len(arr)
siftDown := func(start, end int) {
root := start
for root*2+1 <= end {
child := root*2 + 1
if child+1 <= end && arr[child] < arr[child+1] { child++ }
if arr[root] < arr[child] { arr[root], arr[child] = arr[child], arr[root]; root = child } else { return }
}
}
for i := (n - 2) / 2; i >= 0; i-- { siftDown(i, n-1) }
for end := n - 1; end > 0; end-- { arr[0], arr[end] = arr[end], arr[0]; siftDown(0, end-1) }
}Report a problem with this exampleOpens a pre-filled issue on GitHub.