- Published on
The Algorithm Design Manual (3rd) Exercise Solution 'E4-19'
Table of Contents
Introduction
This series is my solutions for algorithm exercises in'The Algorithm Design Manual' 3rd edition.
It's my solutions, not model answers, so if you find some mistakes or more sophisticated solutions, please post in comment area below.
Repository
Exercise 4-19
Question
You wish to store a set of n numbers in either a max-heap or a sorted array. For each application below, state which data structure is better, or if it does not matter. Explain your answers.
- (a) Find the maximum element quickly.
- (b) Delete an element quickly.
- (c) Form the structure quickly.
- (d) Find the minimum element quickly.
Solution
Subproblem (a)
Conclusion
It does not matter.
Analisys
For max-heap, we get maximum by referencing the top of heap (), and for sorted array, which we consider is ascending sorted array, we get by referencing the last element ().
Subproblem (b)
Conclusion
Max-heap is better.
Analisys
Suppose we have a reference to an element to be deleted in advance.
For max-heap, it takes rearrangement time after the deletion, while for sorted array it takes rearrangement time.
Subproblem (c)
Conclusion
Max-heap is better.
Analisys
Construction time comparison:
- Max-heap:
- Sorted array:
Subproblem (d)
Conclusion
Sorted array is better.
Analisys
It takes time for max-heap to find minimum because we must examine all leaf nodes. On the other hand, we get minimum element in sored array in time by referencing the first element.