Heaps Flashcards
1
Q
Heap
A
- A tree which satisfies either of the two heap conditions:
- max-heap condition
- root is >= to both children
- min-heap condition
- root is <= to both children
- max-heap condition
2
Q
Binary Heap
A
- A heap that is also a complete binary tree
- Can be represented implicitly with an array b/c it is complete binary tree
- Can use array indexing to find parents and children
- If indexing from 0
- Parent → floor[(i-1) / 2]
- Child 1 → 2*i + 1
- Child 2 → 2*i + 2
- In general, people are referring to binary heaps when they discuss heaps
3
Q
Heapify
A
- Heapify is the process of moving an element with a higher, or lower, priority to its correct location
- 2 variations
- heapfiy-up
- heapify-down
4
Q
Heapify Up
A
- Heapify up is the process of moving a node with higher priority up the heap
Steps
- If node is None, return
- Compare node with parent node
- If priority is higher, swap values
- Perform heapfiy up on parent node
- Keep going until node is null, or until heap condition is restored
Complexity
Time
Average: O(log n) ♦ Worst: O(log n)
Space
O(1)
5
Q
Heapify Down
A
- Process of moving an element with lower priority down the heap
Steps
- If node is null, return
- Compare node with both children
- If node’s priority is lower than either child
- Then swap with the larger of the two children
- Perform heapify-down on the larger child
- Keep going until heap condition is restored, or until you don’t have children (leaf)
Complexity
Time
Average: O(log n) ♦ Worst: O(log n)
Space
O(1)
6
Q
Binary Heap
Remove Maximum
A
- Process of removing max element (element with highest priority) from heap
Steps
- Store max element (element at index 0)
- Copy last element into index 0
- Decrement array
- Perform heapify down on element at index 0 to move it to its right location
Complexity
Time
Average: O(log n) ♦ Worst: O(log n)
Space
O(1)
7
Q
Binary Heap
Insertion
A
- Process of inserting an element into binary heap
Steps
- Add element to end of array
- Perform heapify up to move element to its correct location
Complexity
Time
Average: O(log n) ♦ Worst: O(log n)
Space
O(1)
8
Q
Binary Heap
Heap Construction
A
2 appraoched to creating a binary heap
- Naive approach - iterative insertion
- Starting with an empty array, add nodes one by one with insert operations
- O(n log n)
- BuildHeap
- O(n)
9
Q
BuildHeap
A
- Algorithm used to transform a normal array into a heap
- Linear time (although it looks O(n log n))
Steps
- __Insert elements into an array
- We ignore leaves, assuming that they are fine where they are
- Determine index of last parent node ⇒ floor[(n - 1)/2]
- Loop from index to front of array, performing heapify-down on each element
- Keep going until loop ends
Complexity
Time
Average: O(n) ♦ Worst: O(n)
Space
O(1)