github.com/grafana/pyroscope@v1.18.0/pkg/util/minheap/minheap.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package minheap
     6  
     7  func Push(h []int64, x int64) []int64 {
     8  	h = append(h, x)
     9  	up(h, len(h)-1)
    10  	return h
    11  }
    12  
    13  func Pop(h []int64) []int64 {
    14  	n := len(h) - 1
    15  	h[0], h[n] = h[n], h[0]
    16  	down(h, 0, n)
    17  	n = len(h)
    18  	h = h[0 : n-1]
    19  	return h
    20  }
    21  
    22  func up(h []int64, j int) {
    23  	for {
    24  		i := (j - 1) / 2 // parent
    25  		if i == j || (h[j] >= h[i]) {
    26  			break
    27  		}
    28  		h[i], h[j] = h[j], h[i]
    29  		j = i
    30  	}
    31  }
    32  
    33  func down(h []int64, i0, n int) bool {
    34  	i := i0
    35  	for {
    36  		j1 := 2*i + 1
    37  		if j1 >= n || j1 < 0 { // j1 < 0 after int overflow
    38  			break
    39  		}
    40  		j := j1 // left child
    41  		if j2 := j1 + 1; j2 < n && h[j2] < h[j1] {
    42  			j = j2 // = 2*i + 2  // right child
    43  		}
    44  		if h[j] >= h[i] {
    45  			break
    46  		}
    47  		h[i], h[j] = h[j], h[i]
    48  		i = j
    49  	}
    50  	return i > i0
    51  }