mirror of
https://github.com/duke-git/lancet.git
synced 2026-03-01 00:35:28 +08:00
feat: add BuildMaxHeap
This commit is contained in:
@@ -25,6 +25,20 @@ func NewMaxHeap[T any](comparator lancetconstraints.Comparator) *MaxHeap[T] {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BuildMaxHeap builds a MaxHeap instance with data and given comparator.
|
||||||
|
func BuildMaxHeap[T any](data []T, comparator lancetconstraints.Comparator) *MaxHeap[T] {
|
||||||
|
heap := &MaxHeap[T]{
|
||||||
|
data: make([]T, 0),
|
||||||
|
comparator: comparator,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, v := range data {
|
||||||
|
heap.Push(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
return heap
|
||||||
|
}
|
||||||
|
|
||||||
// Push value into the heap
|
// Push value into the heap
|
||||||
func (h *MaxHeap[T]) Push(value T) {
|
func (h *MaxHeap[T]) Push(value T) {
|
||||||
h.data = append(h.data, value)
|
h.data = append(h.data, value)
|
||||||
|
|||||||
@@ -20,6 +20,20 @@ func (c *intComparator) Compare(v1, v2 any) int {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestMaxHeap_BuildMaxHeap(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestMaxHeap_BuildMaxHeap")
|
||||||
|
|
||||||
|
values := []int{6, 5, 2, 4, 7, 10, 12, 1, 3, 8, 9, 11}
|
||||||
|
heap := BuildMaxHeap(values, &intComparator{})
|
||||||
|
|
||||||
|
expected := []int{12, 9, 11, 4, 8, 10, 7, 1, 3, 5, 6, 2}
|
||||||
|
assert.Equal(expected, heap.data)
|
||||||
|
|
||||||
|
assert.Equal(12, heap.Size())
|
||||||
|
|
||||||
|
heap.PrintStructure()
|
||||||
|
}
|
||||||
|
|
||||||
func TestMaxHeap_Push(t *testing.T) {
|
func TestMaxHeap_Push(t *testing.T) {
|
||||||
assert := internal.NewAssert(t, "TestMaxHeap_Push")
|
assert := internal.NewAssert(t, "TestMaxHeap_Push")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user