From 0c6d4ed2e499e3e17165e43803d0d1c6dd0956d9 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Sun, 2 Apr 2023 20:22:13 +0300 Subject: initial generics --- queue/heappriority.go | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) (limited to 'queue/heappriority.go') diff --git a/queue/heappriority.go b/queue/heappriority.go index b607e2c..bfcae71 100644 --- a/queue/heappriority.go +++ b/queue/heappriority.go @@ -4,13 +4,13 @@ import ( "codeberg.org/snonux/algorithms/ds" ) -type HeapPriority struct { - ElementaryPriority +type HeapPriority[T ds.Number] struct { + ElementaryPriority[T] } -func NewHeapPriority(capacity int) *HeapPriority { - q := HeapPriority{ - ElementaryPriority: ElementaryPriority{make(ds.ArrayList, 0, capacity), capacity}, +func NewHeapPriority[T ds.Number](capacity int) *HeapPriority[T] { + q := HeapPriority[T]{ + ElementaryPriority: ElementaryPriority[T]{make(ds.ArrayList[T], 0, capacity), capacity}, } // Index 0 unused @@ -18,20 +18,20 @@ func NewHeapPriority(capacity int) *HeapPriority { return &q } -func (q *HeapPriority) Empty() bool { +func (q *HeapPriority[T]) Empty() bool { return q.Size() == 0 } -func (q *HeapPriority) Size() int { +func (q *HeapPriority[T]) Size() int { return len(q.a) - 1 } -func (q *HeapPriority) Insert(a int) { +func (q *HeapPriority[T]) Insert(a T) { q.a = append(q.a, a) q.swim(len(q.a) - 1) } -func (q *HeapPriority) Max() (max int) { +func (q *HeapPriority[T]) Max() (max T) { if q.Empty() { return 0 } @@ -39,7 +39,7 @@ func (q *HeapPriority) Max() (max int) { return q.a[1] } -func (q *HeapPriority) DeleteMax() int { +func (q *HeapPriority[T]) DeleteMax() T { switch q.Size() { case 0: return 0 @@ -60,14 +60,14 @@ func (q *HeapPriority) DeleteMax() int { } } -func (q *HeapPriority) swim(k int) { +func (q *HeapPriority[T]) swim(k int) { for k > 1 && q.a[k/2] < q.a[k] { q.a.Swap(k/2, k) k = k / 2 } } -func (q *HeapPriority) sink(k int) { +func (q *HeapPriority[T]) sink(k int) { // Last index max := len(q.a) - 1 -- cgit v1.2.3