320 likes | 453 Views
Chapter 21 The Binary Heap. Bernard Chen Spring 2006. What’s priority queue. Problem: find MIN and Delete . Possible methods: unsorted array sorted array Binary Search tree. What’s Binary Heap.
E N D
Chapter 21The Binary Heap Bernard Chen Spring 2006
Problem: find MIN and Delete • Possible methods: • unsorted array • sorted array • Binary Search tree
What’s Binary Heap • The Binary Heap supports the insertion of new items and delete of MIN item in logarithmic worst-case time. • It uses only an array to implement. (Instead of linked list) • It is the classic method used to implement priority queues
Structure Property • A COMPLETE BINARY TREE is a tree that complete filled.
Advantages of Complete Tree • The height of a complete binary tree is at most logN • Left and right pointers are not needed
Advantages of Complete Tree • The parent is in position i/2 • The left child is in position 2i • The right child is in position 2i+1
Heap-Order property • In a Heap, for every node X with parent P, the key in P is smaller than or equal to the key in X
21.2 Implementation of the Basic Operations • Insert operation • Delete operation
21.2.1 The INSERT operation • Insertion is implemented by creating a hole at the next available location and then percolating it up until the new item can be placed in it without violating a heap order. • Insert takes constant time on average but logarithmic time in worst case.
21.2.2 The DeleteMIN Operation • Deletion of the min involves placing the former last item in a hole that is created at the root. • The hole is percolated down the tree through min children until the item can be placed without violating the heap order property.
21.3 the buildHeap Operation:Linear-Time Heap construction • The buildHeap operation can be done in linear time by applying a percolate down routine to nodes in reverse order