Heap Sort - Priority Queue
Heap Sort - Priority Queue
K K Singh 1 12/15/2021
Sorting Revisited
K K Singh 1 12/15/2021
Heaps
14 10
8 7 9 3
2 4 1
14 10
8 7 9 3
2 4 1 1 1 1 1 1
K K Singh 1 12/15/2021
Heaps
A = 16 14 10 8 7 9 3 2 4 1 = 8 7 9 3
2 4 1
K K Singh 1 12/15/2021
Referencing Heap Elements
● So…
Parent(i) { return ⎣i/2⎦; }
Left(i) { return 2*i; }
right(i) { return 2*i + 1; }
● An aside: How would you implement this
most efficiently?
K K Singh 1 12/15/2021
The Heap Property
K K Singh 1 12/15/2021
Heap Height
● Definitions:
● The height of a node in the tree = the number of
edges on the longest downward path to a leaf
● The height of a tree = the height of its root
● What is the height of an n-element heap? Why?
● This is nice: basic heap operations take at most
time proportional to the height of the heap
K K Singh 1 12/15/2021
Heap Operations: Heapify()
K K Singh 1 12/15/2021
Heap Operations: Heapify()
Heapify(A, i)
{
l = Left(i); r = Right(i);
if (l <= heap_size(A) && A[l] > A[i])
largest = l;
else
largest = i;
if (r <= heap_size(A) && A[r] > A[largest])
largest = r;
if (largest != i)
Swap(A, i, largest);
Heapify(A, largest);
}
K K Singh 1 12/15/2021
Heapify() Example
1
6
1
4
0
1
7 9 3
4
2 8 1
A = 16 4 10 14 7 9 3 2 8 1
K K Singh 1 12/15/2021
Heapify() Example
1
6
1
4
0
1
7 9 3
4
2 8 1
A = 16 4 10 14 7 9 3 2 8 1
K K Singh 1 12/15/2021
Heapify() Example
1
6
1
4
0
1
7 9 3
4
2 8 1
A = 16 4 10 14 7 9 3 2 8 1
K K Singh 1 12/15/2021
Heapify() Example
1
6
1 1
4 0
4 7 9 3
2 8 1
A = 16 14 10 4 7 9 3 2 8 1
K K Singh 1 12/15/2021
Heapify() Example
1
6
1 1
4 0
4 7 9 3
2 8 1
A = 16 14 10 4 7 9 3 2 8 1
K K Singh 1 12/15/2021
Heapify() Example
1
6
1 1
4 0
4 7 9 3
2 8 1
A = 16 14 10 4 7 9 3 2 8 1
K K Singh 1 12/15/2021
Heapify() Example
1
6
1 1
4 0
8 7 9 3
2 4 1
A = 16 14 10 8 7 9 3 2 4 1
K K Singh 1 12/15/2021
Heapify() Example
1
6
1 1
4 0
8 7 9 3
2 4 1
A = 16 14 10 8 7 9 3 2 4 1
K K Singh 1 12/15/2021
Heapify() Example
1
6
1 1
4 0
8 7 9 3
2 4 1
A = 16 14 10 8 7 9 3 2 4 1
K K Singh 1 12/15/2021
Analyzing Heapify(): Informal
K K Singh 1 12/15/2021
Analyzing Heapify(): Formal
K K Singh 1 12/15/2021
Analyzing Heapify(): Formal
● So we have
T(n) ≤ T(2n/3) + Θ(1)
T(n) = O(lg n)
● Thus, Heapify() takes logarithmic time
K K Singh 1 12/15/2021
Heap Operations: BuildHeap()
K K Singh 1 12/15/2021
BuildHeap()
// given an unsorted array A, make A a heap
BuildHeap(A)
{
heap_size(A) = length(A);
for (i = ⎣length[A]/2⎦ downto 1)
Heapify(A, i);
}
K K Singh 1 12/15/2021
BuildHeap() Example
1 3
1 1
2 9
6 0
1
8 7
4
K K Singh 1 12/15/2021
Analyzing BuildHeap()
K K Singh 1 12/15/2021
Analyzing BuildHeap(): Tight
K K Singh 1 12/15/2021
Heapsort
K K Singh 1 12/15/2021
Heapsort
Heapsort(A)
{
BuildHeap(A);
for (i = length(A) downto 2)
{
Swap(A[1], A[i]);
heap_size(A) -= 1;
Heapify(A, 1);
}
}
K K Singh 1 12/15/2021
Analyzing Heapsort
K K Singh 1 12/15/2021
Priority Queues
K K Singh 1 12/15/2021
Priority Queue Operations
K K Singh 1 12/15/2021
Any Query??