Tags: java python algorithm heap
A heap is a specialized tree-based data structure that satisfies the heap property: for every node \(i\) other than the root, \(A[\text{parent}(i)] \ge A[i]\) (Max-Heap) or \(A[\text{parent}(i)] \le A[i]\) (Min-Heap).
Root: \(A[1]\)Parent(i): \(\lfloor i/2 \rfloor\)Left(i): \(2i\)Right(i): \(2i + 1\)Assumes the left and right subtrees of node \(i\) are already max-heaps, but \(A[i]\) might be smaller than its children. It "bubbles down" \(A[i]\) to its correct position.
Converts an unordered array into a max-heap by calling Max-Heapify on all non-leaf nodes in bottom-up order (from \(n/2\) down to \(1\)).
heapsize and call Max-Heapify on the new root.A Max-Priority Queue maintains a set \(S\) and supports:
// Min Heap (Default)
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
// Max Heap
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
// Operations
minHeap.offer(10); // Insert - O(log n)
minHeap.peek(); // Maximum - O(1)
minHeap.poll(); // Extract-Min - O(log n)
import heapq
# Min Heap (Default)
min_heap = []
heapq.heapify(min_heap) # O(n)
# Operations
heapq.heappush(min_heap, 10) # Insert - O(log n)
heapq.heappop(min_heap) # Extract-Min - O(log n)
min_heap[0] # Minimum - O(1)
# Max Heap: Use negative values