Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Heap sort and priority queue implementation in Python #19

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions Algorithms/heap_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
def heapify_max(arr, size, index):
left = 2*index + 1
right = 2*index + 2
highest = index

if left < size and arr[highest] < arr[left]:
highest = left
if right < size and arr[highest] < arr[right]:
highest = right

if highest != index:
arr[highest], arr[index] = arr[index], arr[highest]
heapify_max(arr, size, highest)

def heap_sort(arr):
n = len(arr)
for i in range(n//2 - 1, -1, -1):
heapify_max(arr, n, i)
for i in range(n - 1, 0, -1):
arr[0], arr[i] = arr[i], arr[0]
heapify_max(arr, i, 0)

arr = [35, 33, 42, 10, 14, 19, 27, 44, 26, 31]
# heapify_max(arr, len(arr), 0)
# heap_sort(arr)
# print(arr)
39 changes: 39 additions & 0 deletions Algorithms/priority_queue.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Priority queue implementation using heap

import heapq

class PriorityQueue:
def __init__ (self):
self.pq = []

def enqueue(self, priority, item):
self.pq.append(((priority, item)))
heapq._heapify_max(self.pq)

def dequeue(self):
if self.is_empty():
return "Can't dequeue from an empty priority queue!"
return f"Dequeued: {heapq._heappop_max(self.pq)[1]}"

def is_empty (self):
return len(self.pq) == 0

def peek (self):
return "Priority queue empty!" if self.is_empty() else f"Top element: {self.pq[0][1]}"

def print_queue (self):
return f"Priority Queue: {self.pq}"

pq = PriorityQueue()
print(pq.dequeue())
pq.enqueue(3, 45)
pq.enqueue(7, 23)
pq.enqueue(1, 25)
pq.enqueue(5, 15)
pq.enqueue(4, 35)
print(pq.peek())
print(pq.print_queue())
print(pq.dequeue())
print(pq.print_queue())
print(pq.dequeue())
print(pq.print_queue())