Created
November 22, 2021 01:56
-
-
Save rexsimiloluwah/932b89dd3c36d687be0e743a9d3f61be 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) | |
pq.Display() //Returns [10,5,8,6,1] | |
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 [6,1] | |
} | |
// 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 in its exact location | |
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.") | |
} | |
if p.IsEmpty() { | |
p.data = append(p.data, newElement) | |
p.size++ | |
return | |
} | |
p.data = append(p.data, newElement) | |
i := p.size - 1 | |
for i >= 0 { | |
if p.data[i].priority > priority { | |
p.data[i+1] = p.data[i] | |
i-- | |
} else { | |
break | |
} | |
} | |
p.data[i+1] = newElement | |
p.size++ | |
} | |
// Returns and Removes the first element of the priority queue | |
func (p *PriorityQueue) Dequeue() QueueElement { | |
if p.IsEmpty() { | |
panic("Queue is empty.") | |
} | |
dequeued := p.data[0] | |
p.data = p.data[1:] | |
p.size-- | |
return dequeued | |
} | |
// Returns the first element in the queue without modifying the queue | |
func (p *PriorityQueue) Peek() interface{} { | |
if p.IsEmpty() { | |
panic("Queue is empty.") | |
} | |
return p.data[0] | |
} | |
// 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