Previous Lecture Lecture 15 Next Lecture

Lecture 15, Tue 05/23

Priority Queues, Heaps

Recorded Lecture: 5_23_23

Priority Queues

Tree Properties

Heaps

MaxHeap.png

MinHeap.png

HeapArray.png

Insertion into a MaxHeap Steps

  1. insert the element in the first available location
    • Keeps the binary tree complete
  2. While the element’s parent is less than the element
    • Swap the element with its parent

MaxHeapInsertion.png

Removing Max (root) element in a MaxHeap Steps

  1. Copy the root element into a variable
  2. Assign the last_element in the Python List to the root position
  3. While new_root is less than one of its children
    • Swap the largest child with the new_root
  4. Return the original root element

ExtractRoot.png

MinHeap Implementation (from textbook)

# MinHeap
class BinHeap:
	def __init__(self):
		self.heapList = [0]
		self.currentSize = 0

	def percUp(self,i):
		while i // 2 > 0:
			if self.heapList[i] < self.heapList[i // 2]:
				tmp = self.heapList[i // 2]
				self.heapList[i // 2] = self.heapList[i]
				self.heapList[i] = tmp
			i = i // 2

	def insert(self,k):
		self.heapList.append(k)
		self.currentSize = self.currentSize + 1
		self.percUp(self.currentSize)

	def percDown(self,i):
		while (i * 2) <= self.currentSize:
			mc = self.minChild(i)
			if self.heapList[i] > self.heapList[mc]:
				tmp = self.heapList[i]
				self.heapList[i] = self.heapList[mc]
				self.heapList[mc] = tmp
			i = mc

	def minChild(self,i):
		if i * 2 + 1 > self.currentSize:
			return i * 2
		else:
			if self.heapList[i*2] < self.heapList[i*2+1]:
				return i * 2
			else:
				return i * 2 + 1

	def delMin(self):
		retval = self.heapList[1]
		self.heapList[1] = self.heapList[self.currentSize]
		self.currentSize = self.currentSize - 1
		self.heapList.pop()
		self.percDown(1)
		return retval
# pytest
def test_BinHeap():
	bh = BinHeap()
	bh.insert(5)
	bh.insert(7)
	bh.insert(3)
	bh.insert(11)
	assert bh.delMin() == 3
	assert bh.delMin() == 5
	assert bh.delMin() == 7
	assert bh.delMin() == 11