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) }
}How it works
Heapsort Build And Extract Max (Go) reduces to the function heapsort.
Repetition is confined to for root*2+1 <= end — the rest of the file is straight-line.
Applying it
Entry signature: func heapsort(arr []int)
Statements that matter
if arr[root] < arr[child] { arr[root], arr[child] = arr[child], arr[root]; root = child } else { return }
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `heapsort` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.