Heaps Heaps A heap is a binary tree
Heaps
Heaps A heap is a binary tree structure such that the tree is complete or nearly complete The key value of each node is greater than or equal to the key(s) in its descendent K All<=K This is called max-heap; the reversed is min-heap
Heaps 12 24 8 8 12 6 Valid Heap trees 10
Heaps 24 24 12 12 8 6 Valid Heap trees (rule 1)
Heaps 24 44 12 6 44 10 24 10 6 Valid Heap trees (rule 2) 18
Heaps Basic Heap Algorithms Two operations are performed on heap: insert and delete Two basic algorithms are used to maintain the heap tree Reheape. Up (used when inserting a new node) Reheap. Down (used when deleting the root)
Heaps Basic Heap Algorithms Reheape. Up operation repairs a broken heap by floating the last element up the tree until it is in its correct location in the heap 24 12 6 24 8 30 30 6 30 8 12 24 6 8 12
Heaps Basic Heap Algorithms Reheape. Down repairs a broken heap by pushing the root down the tree until it is in its correct position in the heap 5 12 6 12 5 8 10 6 12 8 10 10 6 8 5
Heaps Heap data structure Heap is implemented using an array because it is complete or nearly complete tree. A left child at index j has a right sibling at j+1 78 [0] 45 [3] 56 [1] 8 [4] 32 [2] 23 [5] 19 [6] 78 56 32 45 8 23 19 0 1 2 3 4 5 6
Heaps Heap data structure A node at index i has Left child at 2 i +1 Right child at 2 i +2 Parent at |_ (i-1)/2_| 45 [3] 56 [1] 78 [0] 8 [4] 32 [2] 23 [5] 19 [6] 78 56 32 45 8 23 19 0 1 2 3 4 5 6
Heaps Heap data structure A left child at index j has a right sibling at j+1 A right child at index k has a left sibling at k-1 78 [0] 45 [3] 56 [1] 8 [4] 32 [2] 23 [5] 19 [6] 78 56 32 45 8 23 19 0 1 2 3 4 5 6
Heaps Heap data structure In a complete heap of size n, the first leaf found at |_(n/2)_| For the first leaf at index i, the last nonleaf element 78 found at i-1 [0] 45 [3] 56 [1] 8 [4] 32 [2] 23 [5] 19 [6] 78 56 32 45 8 23 19 0 1 2 3 4 5 6
- Slides: 12