2110 A 5 Heaps 1 2110 A 5

  • Slides: 6
Download presentation
2110: A 5: Heaps 1

2110: A 5: Heaps 1

2110: A 5: Heaps A 5 is now available. You will implement class Heap.

2110: A 5: Heaps A 5 is now available. You will implement class Heap. A Heap object can be a min-heap or a max-heap. A 5 will be used in A 6, which will be to find the shortest path in a graph from a start node to all other nodes. 2

2110: A 5: Heaps A 5 is now available. You will implement class Heap.

2110: A 5: Heaps A 5 is now available. You will implement class Heap. A Heap object can be a min-heap or a max-heap. 5 7 6 b 5 7 6 min-heap (taskx , 5) (tasky , 7) (taskz , 6) min-heap b ( taskx, 5) ( tasky, 7) (taskz , 6) element in the heap: (value, priority) 3

2110: A 5: Heaps (taskx , 5) (tasky , 7) (taskz , 6) min-heap

2110: A 5: Heaps (taskx , 5) (tasky , 7) (taskz , 6) min-heap b ( taskx, 5) ( tasky, 7) (taskz , 6) element in the heap: (value, priority) All operations take O(log heap-size) time Suppose we want to change the priority of taskz to 3. What is the first thing to do? Tell me in English. Have to find taskz in array b. How much time does that take, average or worst case O(…)? Have to find taskz in array b. average or worst case: O(heap-size)!!! 4

2110: A 5: Heaps (taskx , 5) (tasky , 7) (taskz , 6) min-heap

2110: A 5: Heaps (taskx , 5) (tasky , 7) (taskz , 6) min-heap b ( taskx, 5) ( tasky, 7) (taskz , 6) element in the heap: (value, priority) All operations take O(log heap-size) time Except update. Priority(task, p): O(heap-size) taskx is in b[0] tasky is in b[1] taskz is in b[2] Information needed, and quickly Whenever a change of functionality messes up time/space requirement, see whether data structure can be modified or a new one added to alleviate the problem. 5

2110: A 5: Heaps (taskx , 5) b ( taskx, 5) ( tasky, 7)

2110: A 5: Heaps (taskx , 5) b ( taskx, 5) ( tasky, 7) (taskz , 6) (tasky , 7) (taskz , 6) min-heap Hash. Map<E, Integer> map contains the pairs (taskx, 0) (tasky, 1) (taskz, 2) taskx is in b[0] tasky is in b[1] taskz is in b[2] element in the heap: (value, priority) Info needed, quickly All operations take O(log heap-size) time Except update. Priority(task, p): O(heap-size) index= map. get(taskz): average time: O(1) worst-case time: O(heap-size) 6