Created
November 22, 2021 01:17
-
-
Save rexsimiloluwah/28e6c45dccaa08468c193d5883f55e99 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type QueueElement struct { | |
value interface{} | |
priority int | |
} | |
type PriorityQueue struct { | |
maxSize int | |
data []QueueElement | |
size int | |
} | |
//... | |
func main(){ | |
pq := PriorityQueue{} | |
pq.SetMaxSize(10) | |
pq.Enqueue(1, 5) | |
pq.Enqueue(5, 2) | |
pq.Enqueue(6, 3) | |
pq.Enqueue(10, 1) | |
pq.Enqueue(8, 2) | |
fmt.Println(pq.Dequeue()) //Returns {10 1} | |
fmt.Println(pq.Dequeue()) //Returns {5 2} | |
fmt.Println(pq.Dequeue()) //Returns {8 2} | |
fmt.Println(pq.Peek()) //Returns {6 3} | |
pq.Display() //Displays [1,6] | |
} | |
// Sets the max-size of the priority queue | |
func (p *PriorityQueue) SetMaxSize(maxSize int) { | |
p.maxSize = maxSize | |
} | |
// Checks if the priority queue is empty | |
func (p *PriorityQueue) IsEmpty() bool { | |
return p.size == 0 | |
} | |
// Adds a new element to the priority queue (unsorted array case) | |
func (p *PriorityQueue) Enqueue(el interface{}, priority int) { | |
newElement := QueueElement{el, priority} | |
if p.size == p.maxSize { | |
panic("Queue has reached its max size limit.") | |
} | |
p.data = append(p.data, newElement) | |
p.size++ | |
} | |
// Removes and returns the element with the min-priority from the PQ | |
func (p *PriorityQueue) Dequeue() QueueElement { | |
if p.IsEmpty() { | |
panic("Queue is empty.") | |
} | |
idx := 0 | |
// Traverse through the unsorted array to find the element with the smallest min-priority | |
for i := 0; i < p.size; i++ { | |
if p.data[i].priority < p.data[idx].priority { | |
idx = i | |
} | |
} | |
dequeuedEl := p.data[idx] | |
// Remove the dequeued element from the PQ | |
p.data = append(p.data[:idx], p.data[idx+1:]...) | |
p.size-- | |
return dequeuedEl | |
} | |
// Peek (Returns the element with the min-priority from the PQ) | |
func (p *PriorityQueue) Peek() QueueElement { | |
if p.IsEmpty() { | |
panic("Queue is empty.") | |
} | |
dequeuedEl := p.data[0] | |
// Traverse through the unsorted array to find the element with the min-priority | |
for _, el := range p.data { | |
if el.priority < dequeuedEl.priority { | |
dequeuedEl = el | |
} | |
} | |
return dequeuedEl | |
} | |
// Display the elements of the queue in an array form | |
func (p *PriorityQueue) Display() { | |
if p.IsEmpty() { | |
panic("Queue is empty.") | |
} | |
arr := make([]interface{}, p.size) | |
i := 0 | |
for i < p.size { | |
arr[i] = p.data[i].value | |
i++ | |
} | |
fmt.Println("Priority Queue elements: ", arr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment