// this package is mostly copy-pasted from golang's std container/heap // I changed Interface, Pop and Push in order to get rid of type assertions // usage can be found in test file, benchmarks show that we can get about 27% of speedup for 1000 elems, or 10% for 10M elems (tested on go1.4) package gheap type Interface interface { Len() int Less(i, j int) bool Swap(i, j int) } func Init(h Interface) { // heapify n := h.Len() for i := n/2 - 1; i >= 0; i-- { down(h, i, n) } } // put new element at Len() position before calling Push(h) // you must also increase Len func Push(h Interface) { up(h, h.Len()-1) } // after calling Pop() top element will be at position Len()-1 // you must decrease Len after this call func Pop(h Interface) { n := h.Len() - 1 h.Swap(0, n) down(h, 0, n) } func up(h Interface, j int) { for { i := (j - 1) / 2 // parent if i == j || !h.Less(j, i) { break } h.Swap(i, j) j = i } } func down(h Interface, i, n int) { for { j1 := 2*i + 1 if j1 >= n || j1 < 0 { // j1 < 0 after int overflow break } j := j1 // left child if j2 := j1 + 1; j2 < n && !h.Less(j1, j2) { j = j2 // = 2*i + 2 // right child } if !h.Less(j, i) { break } h.Swap(i, j) i = j } }