200 likes | 224 Views
Learn about implementing priority queues using heaps, a variation of the table ADT. Explore heap operations like deleting and inserting elements for efficient sorting using heapsort. Understand the differences between heapsort, mergesort, and quicksort.
E N D
Tables and Priority Queues Chapter 11
The ADT Table Chapter 11 -- Tables and Priority Queues
Selecting an Implementation Chapter 11 -- Tables and Priority Queues
A Sorted Array-Based Implementation of the ADT Table Chapter 11 -- Tables and Priority Queues
A Binary Search Tree Implementation of the ADT Table Chapter 11 -- Tables and Priority Queues
The ADT Priority Queue: A Variation of the ADT Table Chapter 11 -- Tables and Priority Queues
Heaps • A heap is an ADT that is similar to a binary search tree, although it differs from a binary search tree in two significant ways • A heap is ordered in a much weaker sense • Heaps are always complete binary trees. • So, • A heap is a complete binary tree • 1) that is empty or • 2) Root contains a search key that is greater than or equal to the search key of each of its children, and Whose root has heaps as its subtrees Chapter 11 -- Tables and Priority Queues
Here is the UML diagram for a heap class. Chapter 11 -- Tables and Priority Queues
Because a heap is a complete binary tree, you can use an array-based implementation of a binary tree, as you saw in Chapter 10. Chapter 11 -- Tables and Priority Queues
A Heap Implementation of the ADT Priority Queue • We need the following members: • items: an array of heap items • size: an integer equal to the number of items in the heap. • Now lets talk about the following functions: • heapDelete • heapInsert Chapter 11 -- Tables and Priority Queues
heapDelete • where is the largest element? • rootItem = items[0]; • Now we are left with two disjoint heaps • So we have to fix it. Chapter 11 -- Tables and Priority Queues
Copy the last element up • Items[0] = items[size-1]; • size--; Chapter 11 -- Tables and Priority Queues
Now fix it (trickle down) Chapter 11 -- Tables and Priority Queues
heapInsert • add new item to the end • items[size] = newItem; • size++; • Now fix the heap (float the new item up to the correct location) Chapter 11 -- Tables and Priority Queues
Heapsort • Strategy • Transforms the array into a heap • Removes the heap's root (the largest element) by exchanging it with the heap’s last element • Transforms the resulting semiheap back into a heap Chapter 11 -- Tables and Priority Queues
Heapsort • Compared to mergesort • Both heapsort and mergesort are O(n * log n) in both the worst and average cases • However, heapsort does not require a second array • Compared to quicksort • Quicksort is O(n * log n) in the average case • It is generally the preferred sorting method, even though it has poor worst-case efficiency : O(n2) Chapter 11 -- Tables and Priority Queues
Heapsort Chapter 11 -- Tables and Priority Queues
Summary Chapter 11 -- Tables and Priority Queues