I wonder what’s the algorithm of make_heap in in C++ such that the complexity is 3*N? Only way I can think of to make a heap by inserting elements have complexity of O(N Log N). Thanks a lot!
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You represent the heap as an array. The two elements below the
i‘th element are at positions2i+1and2i+2. If the array hasnelements then, starting from the end, take each element, and let it "fall" to the right place in the heap. This isO(n)to run.Why? Well for
n/2of the elements there are no children. Forn/4there is a subtree of height 1. Forn/8there is a subtree of height 2. Forn/16a subtree of height 3. And so on. So we get the seriesn/22 + 2n/23 + 3n/24 + ... = (n/2)(1 * (1/2 + 1/4 + 1/8 + . ...) + (1/2) * (1/2 + 1/4 + 1/8 + . ...) + (1/4) * (1/2 + 1/4 + 1/8 + . ...) + ...) = (n/2) * (1 * 1 + (1/2) * 1 + (1/4) * 1 + ...) = (n/2) * 2 = n. Or, formatted maybe more readably to see the geometric series that are being summed:And the trick we used repeatedly is that we can sum the geometric series with
So the total number of "see if I need to fall one more, and if so which way do I fall? comparisons comes to
n. But you get round-off from discretization, so you always come out to less thannsets of swaps to figure out. Each of which requires at most 3 comparisons. (Compare root to each child to see if it needs to fall, then the children to each other if the root was larger than both children.)