Analyze quicksort and heapsort
Analyze quicksort and heapsort
Quicksort partitions a slice around a pivot and recursively sorts the partitions. Balanced partitions give O(n log n) time; consistently unbalanced partitions can cost O(n²). Heapsort instead builds a max heap, a tree represented in an array where each parent is at least as large as its children, then repeatedly moves its maximum to the end.
package main
import ( "fmt")
func quick(a []int) { if len(a) < 2 { return } p := a[len(a)-1] i := 0 for j := 0; j < len(a)-1; j++ { if a[j] < p { a[i], a[j] = a[j], a[i] i++ } } a[i], a[len(a)-1] = a[len(a)-1], a[i] quick(a[:i]) quick(a[i+1:])}func main() { a := []int{5, 1, 4, 1, 3} quick(a) fmt.Println(a)}Before each partition step, elements before i are smaller than the pivot; the processed elements between i and j are at least the pivot. Placing the pivot fixes its final position. This simple last-pivot implementation is unstable and can require O(n) recursion depth for sorted or equal input; use it for learning, not untrusted large inputs.
Expected output:
[1 1 3 4 5]Sift down and extract the maximum
package main
import ( "fmt")
func sift(a []int, i, n int) { for i < n/2 { j := 2*i + 1 if j+1 < n && a[j+1] > a[j] { j++ } if a[i] >= a[j] { return } a[i], a[j] = a[j], a[i] i = j }}func heapSort(a []int) { for i := len(a)/2 - 1; i >= 0; i-- { sift(a, i, len(a)) } for n := len(a); n > 1; { a[0], a[n-1] = a[n-1], a[0] n-- sift(a, 0, n) }}func main() { a := []int{7, 2, 6, 2, 0} heapSort(a) fmt.Println(a)}Children of i have indices 2i+1 and 2i+2 when present. Sifting chooses the larger child to restore the heap property. Bottom-up heap construction takes O(n); each extraction costs O(log n), so worst-case time O(n log n), O(1) auxiliary space here. This sort is not stable. The standard library may use different implementation strategies; do not infer them from these examples.
Expected output:
[0 2 2 6 7]Try it locally
Use slices.Sort to sort []int{8,8,-2,3}, then compare against the expected values using slices.Equal. Explain why library sorting is preferable to the naive pivot routine.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Algorithms 04: Analyze quicksort and heapsort
Check the lesson objective before moving on.
What input can make last-element-pivot quicksort quadratic?
What property holds in the max heap before extraction?