package minheap

import 

type entry[,  any] struct {
	key   
	value 
}

// A Heap is a minimum heap ordered by key.
type Heap[ cmp.Ordered,  any] []entry[, ]

func ( Heap[, ]) () int    { return len() }
func ( Heap[, ]) () bool { return len() == 0 }

// Peek returns the smallest element in the heap.
// It must not be called when the heap is empty.
func ( Heap[, ]) () (, ) {
	 := [0]
	return .key, .value
}

// Push adds an element to the heap.
func ( *Heap[, ]) ( ,  ) {
	* = append(*, entry[, ]{key: , value: })
	(*).up(len(*) - 1)
}

// Pop removes and returns the smallest element in the heap.
// It must not be called when the heap is empty.
func ( *Heap[, ]) () (, ) {
	 := *
	 := len() - 1
	 := [0]
	[0] = []
	var  entry[, ]
	[] = 
	 = [:]
	if  > 0 {
		.down(0)
	}
	* = 
	return .key, .value
}

// Clear removes all elements from the heap.
func ( *Heap[, ]) () {
	clear(*)
	* = (*)[:0]
}

func ( Heap[, ]) ( int) {
	for  > 0 {
		 := ( - 1) / 2
		if [].key <= [].key {
			return
		}
		[], [] = [], []
		 = 
	}
}

func ( Heap[, ]) ( int) {
	for {
		 := 2* + 1
		if  >= len() {
			break
		}
		if  :=  + 1;  < len() && [].key < [].key {
			 = 
		}
		if [].key <= [].key {
			break
		}
		[], [] = [], []
		 = 
	}
}