Balanced binary tree implementation of priority queues in Kotlin
- Insertion:
O(log n)
- Removal:
O(log n)
- Returning max or min:
O(1)
-
Min Priority Queues:
Removing and inserting to the priority queue uses helper functionsheapifyDown()
andheapifyUp()
to maintain heap properties.class MinPriorityQueue<T: Comparable<T>> : PriorityQueue<T>() { fun removeMin(): T? { if (isEmpty()) return null if (size == 1) return heapArray.removeAt(0) val minElement = heapArray[0] heapArray[0] = heapArray.removeAt(size - 1) heapifyDown() return minElement } fun insertItem(item: T) { heapArray.add(item) heapifyUp(size - 1) } fun min(): T? { return heapArray.firstOrNull() } }
-
Max Priority Queues:
They also maintain heap properties using the helper functions.class MaxPriorityQueue<T: Comparable<T>> : PriorityQueue<T>() { fun removeMax(): T? { if (isEmpty()) return null if (size == 1) return heapArray.removeAt(0) val maxElement = heapArray[0] heapArray[0] = heapArray.removeAt(size - 1) heapifyDown() return maxElement } fun insertItem(item: T) { heapArray.add(item) heapifyUp(size - 1) } fun max(): T? { return heapArray.firstOrNull() } }