300 likes | 562 Views
Design and Analysis of Algorithms. Lecture # 15 BCS. Build-Max-Heap(A). Running time of Max- Heapify O(h) n-element heap has height floor( lgn ) Max. nodes of height h are Ceiling(n/2 h+1 ). Build-Max-Heap(A). HeapSort(A). Build-Max-Heap(A) for i ← length [A] downto 2
E N D
Design and Analysis of Algorithms Lecture # 15 BCS Muhammad Umair
Build-Max-Heap(A) • Running time of Max-Heapify • O(h) • n-element heap has height • floor(lgn) • Max. nodes of height h are • Ceiling(n/2h+1) Muhammad Umair
Build-Max-Heap(A) Muhammad Umair
HeapSort(A) • Build-Max-Heap(A) • for i ← length [A] downto 2 • do exchange A[1] ↔ A[i] • Heap-size[A] ← heap-size[A] – 1 • Max-HeapIFY(A,1) Muhammad Umair
Heapsort(A)[16,14,10,8,7,9,3,2,4,1] Muhammad Umair
Heapsort(A)[16,14,10,8,7,9,3,2,4,1] Muhammad Umair
Heapsort(A)[16,14,10,8,7,9,3,2,4,1] Muhammad Umair
Heapsort(A)[16,14,10,8,7,9,3,2,4,1] Muhammad Umair
Heapsort(A)[16,14,10,8,7,9,3,2,4,1] Muhammad Umair
Heapsort(A)[16,14,10,8,7,9,3,2,4,1] Muhammad Umair
Heapsort(A)[16,14,10,8,7,9,3,2,4,1] Muhammad Umair
Heapsort(A)[16,14,10,8,7,9,3,2,4,1] Muhammad Umair
Heapsort(A)[16,14,10,8,7,9,3,2,4,1] Muhammad Umair
Heapsort(A)[16,14,10,8,7,9,3,2,4,1] Muhammad Umair
Analysis of Heap Algorithms • Max-HeapIFY(A,i) • O (lg n) = O (h) • Build-Max-Heap(A) • O (n) • HeapSort(A) • O (n lg n) Muhammad Umair
Student Exercise • Priority Queues • Max-priority queue • Min-priority queue Muhammad Umair
Quick Sort (A, p, r) • if p < r then • Q ← Partition (A, p, r) • Quick Sort (A, p, q – 1) • Quick Sort (A, q + 1, r) Muhammad Umair
PARTITION (A, p, r) • x ← A [ r] • i ← p – 1 • for j ← p to r – 1 do • If A [ j] <= x then • i ← i + 1 • exchange A [ i ] & A [ j] • exchange A [ i + 1] & A [ r] • return i + 1 Muhammad Umair
Analysis of Quick Sort • Worst Case Partitioning • Best Case Partitioning • Balanced Partitioning Muhammad Umair
Worst Case Partitioning • The maximum running time • Pivot element is already on its actual location • It means the input data is also sorted form • Its recurrence : T(n) = T(0)+T(n-1)+Θ(n) • The solution : T(n) = Θ(n2) Muhammad Umair
Best Case Partitioning • The best running time • Pivot element is always be placed at the mid location • It means the input data will be split into 2-partitions of approximately same size • Its recurrence : T(n) <= 2T(n /2)+Θ(n) • The solution : T(n) = O( n lg n) Muhammad Umair
Balanced Partitioning • The average running time • It means the input data will be split into 2-partitions of different size • Its recurrence : T (n)<= T(9n/10) + T (n/10) +Θ(n) • The solution : T (n) = O( n lg n) Muhammad Umair
Summary • Quick Sort • Analysis • Worst Case • Best Case • Balanced Partitioning Muhammad Umair