From a1984f0a5981fe76cae337ed619d8828d5d46174 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Mon, 22 Aug 2022 10:51:37 +0800 Subject: [PATCH] feat: add BuildMaxHeap --- datastructure/heap/maxheap.go | 14 ++++++++++++++ datastructure/heap/maxheap_test.go | 14 ++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/datastructure/heap/maxheap.go b/datastructure/heap/maxheap.go index 98b07fa..81e20c5 100644 --- a/datastructure/heap/maxheap.go +++ b/datastructure/heap/maxheap.go @@ -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 func (h *MaxHeap[T]) Push(value T) { h.data = append(h.data, value) diff --git a/datastructure/heap/maxheap_test.go b/datastructure/heap/maxheap_test.go index bd3c0ee..fd07f65 100644 --- a/datastructure/heap/maxheap_test.go +++ b/datastructure/heap/maxheap_test.go @@ -20,6 +20,20 @@ func (c *intComparator) Compare(v1, v2 any) int { 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) { assert := internal.NewAssert(t, "TestMaxHeap_Push")