-1

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)
}
Steve
  • 863
  • 3
  • 9
  • 21

1 Answers1

3

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
}
ParsaAlizadeh
  • 78
  • 1
  • 4