Is golang container/heap effectively doing heap sort?

642 Views Asked by At

Is golang container/heap effectively doing heap sort on an underlying slice?

It doesn't look like underlying array is always sorted.

type IntHeap []int
// ... other interface implementation
func main() {
    a := []int{}
    h := IntHeap(a)
    heap.Init(&h)
    heap.Push(&h, 3)
    heap.Push(&h, 2)
    heap.Push(&h, 5)
    // underlying array 'a' is not sorted
    fmt.Printf("a: %+v\n", a)
}
1

There are 1 best solutions below

1
ParsaAlizadeh On

The underlying array doesn't have to be sorted. It just represent the binary tree used by heap implemention.

Also heaps don't use heapsort. Heapsort is a way to sort an array using heap.

func main() {
    a := []int{}
    h := IntHeap(a)
    heap.Init(&h)
    heap.Push(&h, 3)
    heap.Push(&h, 2)
    heap.Push(&h, 5)

    // heapsort
    for h.Len() > 0 {
        fmt.Printf("%d ", heap.Pop(&h))
    }
    // output: 2 3 5
}