Lecture 11.1
Lecture 11.1
8 7
6 7 2 6
5 1 57
If the New element is 5, then its okay.
Insertion-Putting An Element Into A Max Heap
8 7
6 7 2 6
5 1 270
If the new element is 20 rather than 5,
then we need to find home for 20.
Insertion-Putting An Element Into A Max Heap
8 7
6 20 2 6
20 7
6 8 2 6
20
9 7
6 8 2 6
5 1 7
Removal of root: The procedure for deleting the root from the heap
(effectively extracting the max/min element in a max-heap or in a min-heap) and
restoring the properties is called down-heap (also known as heapify-down,
cascade-down and extract-min/max).
Delete
1. Replace/exchange the root of the heap with the last element on the last level.
15 7
6 9 2 6
5 1 77 8
15 7
6 9 2 6
5 1 77 8
15 7
6 9 2 6
5 1 77 8
20
15 7
6 9 2 6
5 1 7 20
8 7
6 9 2 6
5 1 7
9 7
6 8 2 6
5 1 7
Goal:
Sort an array using heap representations
Idea:
1. Build a max-heap from the array
2. Swap the root (the maximum element) with the last element in the array
3. “Discard” this last node by decreasing the heap size
4. Call MAX-HEAPIFY on the new root
5. Repeat this process until only one node remains
Alg: HEAPSORT(A)
MAX-HEAPIFY(A, 0, 1)
Uses of Heaps
Each insert and delete operation is O(logN) at the very worst - the heap does
not always have all N values in it.
So, the complexity is certainly no greater than O(NlogN).
Some Important Properties of a Heap
Given n, there exists a unique binary tree with n nodes that is essentially
complete, with
h = log2 n
Heaps are based upon trees. These trees maintain the heap
property.
The Heap invariant. The value of Every Child is greater than the value of the
parent. We are describing Min-heaps here (Use less than for Max-heaps).
The trees must be mostly balanced for the costs listed below to
hold.
Heaps form the basis for an efficient sort called heap sort
that has cost proportional to n*log(n) where n is the number
of elements to be sorted.
Heaps are the data structure most often used to implement
priority queues.
Books
1. https://en.wikipedia.org/wiki/Data_structure