100 likes | 226 Views
Lecture 8. Heaps, Heapsort and Priority Queues. Heap. A binary tree satisfying heap property: data in parent larger than data in children. Examples. Implemented efficiently as an array: fast access time. Space: n. Access: O(1). Heap. Data at parent is larger than data at children
E N D
Lecture 8 Heaps, Heapsort and Priority Queues
Heap • A binary tree satisfying heap property: data in parent larger than data in children. Examples. • Implemented efficiently as an array: fast access time. Space: n. Access: O(1).
Heap • Data at parent is larger than data at children • Tree is binary, balanced, filled left
Operations on Heaps Insert/remove element from heap: trickle up/down. Time: height of tree = O(log n)
Delete Max Remove root, replace with last element.
HeapSort • Heapsort: Variation on Selection Sort, with maximum computed efficiently at each step using a heap. • Step 1: create a heap. In O(n) time. • Then iterate as in Selection Sort. Remove root (max). Readjust tree (move last key to root, trickle down) in O(log n). Continue until all are removed (in sorted order). • Time O(n log n) because removing/readjusting takes log n.
Analysis • Create a heap: insert an element O(log n). Total O(n log n). • Analysis can be improved to O(n) time (read handout, ch. 7.3): start with elements in the arary, heapify for each element. Use nr of elements at height h, < n/2h+1 • Total time: S h n/2h+1 = O(n)
Applications: Priority Queues • Priority Queues: data structure to allow for efficient finding of the minimum/maximum, after initial preprocessing, and maintain it in O(log n) time. Done with heaps. • Used in Operating Systems, to maintain priority queues of processes.
Homework • From handout, ex. 7.1-1,2,3,4,5,6. • 7.2-1,2 • 7.3-1,3 • 7.4-1,2,3. • 7.5-1,2 Extra credit: 7.5-6