CS 332: Algorithms: Introduction To Heapsort
CS 332: Algorithms: Introduction To Heapsort
CS 332: Algorithms: Introduction To Heapsort
Introduction to heapsort
log b a
T ( n) n
log n
f ( n )
log b a
f (n) O n log b a
f ( n) n
log b a
c 1
Sorting Revisited
Heaps
14
10
Heaps
14
10
Heaps
A = 16 14 10 8
10
1 =
2
7
4
Heaps
A = 16 14 10 8
10
1 =
2
7
4
So
Parent(i) { return i/2 ; }
Left(i) { return 2*i; }
right(i) { return 2*i + 1; }
Heap Height
Definitions:
Heapify() Example
16
4
10
14
2
7
8
A = 16 4 10 14 7
Heapify() Example
16
4
10
14
2
7
8
A = 16 4 10 14 7
Heapify() Example
16
4
10
14
2
7
8
A = 16 4 10 14 7
Heapify() Example
16
14
10
4
2
7
8
A = 16 14 10 4
Heapify() Example
16
14
10
4
2
7
8
A = 16 14 10 4
Heapify() Example
16
14
10
4
2
7
8
A = 16 14 10 4
Heapify() Example
16
14
10
8
2
7
4
A = 16 14 10 8
Heapify() Example
16
14
10
8
2
7
4
A = 16 14 10 8
Heapify() Example
16
14
10
8
2
7
4
A = 16 14 10 8
Draw it
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);
}
BuildHeap() Example
2
14
16
8
10
Analyzing BuildHeap()
Each call to Heapify() takes O(lg n) time
There are O(n) such calls (specifically, n/2 )
Thus the running time is O(n lg n)
Heapsort
Heapsort
Heapsort(A)
{
BuildHeap(A);
for (i = length(A) downto 2)
{
Swap(A[1], A[i]);
heap_size(A) -= 1;
Heapify(A, 1);
}
}
Analyzing Heapsort
The call to BuildHeap() takes O(n) time
Each of the n - 1 calls to Heapify() takes
O(lg n) time
Thus the total time taken by HeapSort()
= O(n) + (n - 1) O(lg n)
= O(n) + O(n lg n)
= O(n lg n)
Priority Queues
Heapsort is a nice algorithm, but in practice
Quicksort (coming up) usually wins
But the heap data structure is incredibly useful
for implementing priority queues