github.com/muhammadn/cortex@v1.9.1-0.20220510110439-46bb7000d03d/tools/blocksconvert/builder/heap.go (about) 1 package builder 2 3 // Heap is a binary tree where parent node is "smaller" than its children nodes ("Heap Property"). 4 // Heap is stored in a slice, where children nodes for node at position ix are at positions 2*ix+1 and 2*ix+2. 5 // 6 // Heapify will maintain the heap property for node "ix". 7 // 8 // Building the heap for the first time must go from the latest element (last leaf) towards the element 0 (root of the tree). 9 // Once built, first element is the smallest. 10 // 11 // Element "ix" can be removed from the heap by moving the last element to position "ix", shrinking the heap 12 // and restoring the heap property from index "ix". (This is typically done from root, ix=0). 13 func heapify(length int, ix int, less func(i, j int) bool, swap func(i, j int)) { 14 smallest := ix 15 left := 2*ix + 1 16 right := 2*ix + 2 17 18 if left < length && less(left, smallest) { 19 smallest = left 20 } 21 22 if right < length && less(right, smallest) { 23 smallest = right 24 } 25 26 if smallest != ix { 27 swap(ix, smallest) 28 heapify(length, smallest, less, swap) 29 } 30 }