Container/heap - why does Pop() take the last element, when the first on is smallest?

Looking at the implementation of container/heap. The first element is always the smallest.

Now, how come the Pop() function is supposed to take the last element in the slice, because the container/heap code first swaps the first element with the last, before calling Pop() ?

Does this not seem like a bit counter intuitive, plus doing an extra swap operation ?

func Pop(h Interface) interface{} {
    n := h.Len() - 1
    h.Swap(0, n)
    down(h, 0, n)
    return h.Pop()
}

Is there a legitimate reason for this decision ?

The Swap allows to use the Pop function at the end. And they would be provided by the user through the interface. It is the simplest algorithm.

The Pop function returns the last element of h and remove it from h. A heap would be fine.

This code is the most natural implementation actually.

1 Like

Yes, I see that now. Question solved.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.