An array consists of n elements. We want to create a heap using the elements. The time complexity of building a heap will be in the order ofNote: This kind of question will be helpful in clearing Infosys recruitment.
Question
An array consists of n elements. We want to create a heap using the elements. The time complexity of building a heap will be in the order ofNote: This kind of question will be helpful in clearing Infosys recruitment.
Solution
The time complexity of building a heap with n elements is in the order of O(n).
Here's a step-by-step explanation:
-
A heap can be built by calling the heapify function for each element of the array, starting from the last internal node, and moving to the root node.
-
The heapify function, in the worst case, can take O(logn) time for a tree with n nodes (this is because the tree is a complete binary tree).
-
However, the time complexity for building a heap is not O(nlogn), even though we are calling the heapify function n times. This is because the height of the tree (and therefore the time complexity of the heapify function) is not logn for all elements.
-
Instead, we can calculate the time complexity as follows: for n elements, there are approximately n/2 leaves, n/4 nodes of height 1, n/8 nodes of height 2, etc. Therefore, the maximum number of nodes at height h is n/(2^(h+1)).
-
So, the total number of operations in heapify is the sum of the height of the nodes times the number of nodes at that height, which is approximately n/20 + n/41 + n/82 + n/163 + ... = n(0/2 + 1/4 + 2/8 + 3/16 + ...) = n.
-
Therefore, the time complexity of building a heap is O(n).
Similar Questions
What is the space complexity of Heap Sort?
Operations of Heap Data Structure:
Given an array of element 0, 5, 9, 1, 3, 10, 8, 6,11. Which of the following is the correct sequence when we pop the elements 1 by 1, after inserting all the elements in a min-heap?
Heap can be used as
Which of the following is the valid min heap?
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.