github.com/matrixorigin/matrixone@v1.2.0/pkg/vm/engine/tae/mergesort/heap.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 heap provides heap operations for any type that implements
     6  // heap.Interface. A heap is a tree with the property that each node is the
     7  // minimum-valued node in its subtree.
     8  //
     9  // The minimum element in the tree is the root, at index 0.
    10  //
    11  // A heap is a common way to implement a priority queue. To build a priority
    12  // queue, implement the Heap interface with the (negative) priority as the
    13  // ordering for the Less method, so Push adds items while Pop removes the
    14  // highest-priority item from the queue. The Examples include such an
    15  // implementation; the file example_pq_test.go has the complete source.
    16  package mergesort
    17  
    18  // Init establishes the heap invariants required by the other routines in this package.
    19  // Init is idempotent with respect to the heap invariants
    20  // and may be called whenever the heap invariants may have been invalidated.
    21  // The complexity is Operator(n) where n = len(h).
    22  /*
    23  func heapInit[T any](h *heapSlice[T]) {
    24  	// heapify
    25  	n := len(h.s)
    26  	for i := n/2 - 1; i >= 0; i-- {
    27  		down(h, i, n)
    28  	}
    29  }
    30  */
    31  
    32  // Push pushes the element x onto the heap.
    33  // The complexity is Operator(log n) where n = len(h).
    34  func heapPush[T any](h *heapSlice[T], x heapElem[T]) {
    35  	h.s = append(h.s, x)
    36  	up(h, len(h.s)-1)
    37  }
    38  
    39  // Pop removes and returns the minimum element (according to Less) from the heap.
    40  // The complexity is Operator(log n) where n = len(h).
    41  // Pop is equivalent to Remove(h, 0).
    42  func heapPop[T any](h *heapSlice[T]) heapElem[T] {
    43  	n := len(h.s) - 1
    44  	(h.s)[0], (h.s)[n] = (h.s)[n], (h.s)[0]
    45  	down(h, 0, n)
    46  	res := (h.s)[n]
    47  	h.s = (h.s)[:n]
    48  	return res
    49  }
    50  
    51  func up[T any](h *heapSlice[T], j int) {
    52  	for {
    53  		i := (j - 1) / 2 // parent
    54  		if i == j || !h.Less(j, i) {
    55  			break
    56  		}
    57  		h.Swap(i, j)
    58  		j = i
    59  	}
    60  }
    61  
    62  func down[T any](h *heapSlice[T], i0, n int) bool {
    63  	i := i0
    64  	for {
    65  		j1 := 2*i + 1
    66  		if j1 >= n || j1 < 0 { // j1 < 0 after int overflow
    67  			break
    68  		}
    69  		j := j1 // left child
    70  		if j2 := j1 + 1; j2 < n && h.Less(j2, j1) {
    71  			j = j2 // = 2*i + 2  // right child
    72  		}
    73  		if !h.Less(j, i) {
    74  			break
    75  		}
    76  		h.Swap(i, j)
    77  		i = j
    78  	}
    79  	return i > i0
    80  }