






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







docsity.com
ļ® The āsmallestā element is the first one removed ļ® (You could also define a largest-first-out priority queue) ļ® The definition of āsmallestā is up to the programmer (for example, you might define it by implementing Comparator or Comparable) ļ® If there are several āsmallestā elements, the implementer must decide which to remove first ļ® Remove any āsmallestā element (donāt care which) ļ® Remove the first one added docsity.com
ļ® If we load an array once and do thousands of searches on it, we want to make searching fastāso we would probably sort the array ļ® If we load a huge array and expect to do only a few searches, we probably donāt want to spend time sorting the array
docsity.com
ļ® Adding an element would take O(1) time (why?) ļ® Removing an element would take O(n) time (why?) ļ® Hence, adding and removing an element takes O(n) time ļ® This is an inefficient representation
ļ® Adding an element would take O(n) time (why?) ļ® Removing an element would take O(1) time (why?) ļ® Hence, adding and removing an element takes O(n) time ļ® Again, this is inefficient
docsity.com
ļ® Insertion times would range from O(log n) to O(n) (why?) ļ® Removal times would range from O(log n) to O(n) (why?)
ļ® Insertion and removal could destroy the balance ļ® We need an algorithm to rebalance the binary tree ļ® Good rebalancing algorithms require only O(log n) time, but are complicated
docsity.com
ļ® A priority queue can be implemented as a heap
ļ® In order to do this, we have to define the heap property
ļ® In Heapsort, a node has the heap property if it is at least as large as its children ļ® For a priority queue, we will define a node to have the heap property if it is as least as small as its children (since we are using smaller numbers to represent higher priorities)
Heapsort: Blue node has the heap property
Priority queue: Blue node has the heap property docsity.com
ļ® To add an element:
ļ® Increase lastIndex and put the new value there ļ® Reheap the newly added node ļ® This is called up-heap bubbling or percolating up ļ® Up-heap bubbling requires O(log n) time
ļ® To remove an element:
ļ® Remove the element at location 0 ļ® Move the element at location lastIndex to location 0 , and decrement lastIndex ļ® Reheap the new root node (the one now at location 0 ) ļ® This is called down-heap bubbling or percolating down ļ® Down-heap bubbling requires O(log n) time
ļ® Thus, it requires O(log n) time to add and remove an element
docsity.com
ļ® Simple implementations take O(n) time ļ® Heap implementations take O(log n) time ļ® Balanced binary tree implementations take O(log n) time ļ® Binary tree implementations, without regard to balance, can take O(n) (linear) time
docsity.com