0

A min-heap consist of 2047 elements, the maximum number of comparisons required to determine the maximum number of elements is _.

For this i went with approach as this is a min heap and the min element will be there in the root node. So to find the maximum no we have to go till the end of tree that is till leaf node level and has to compare with all. So comparison will be n-1 but ans is not 2046 its 1043. Can anyone explain it to me how?

2 Answers2

0

You are completely right that the maximum number in a min-heap has to be one of the leaf-nodes of that heap (it must be a leaf node, though it could be any leaf-node). A heap is a complete binary tree, and in the case of 2047 elements it will be a perfect tree (complete with the last level completely filled). In such a tree, there will be exactly 1024 elements on the bottom level of the heap, giving us 1024 candidates for the min.

Because heaps are complete trees, they are typically stored as arrays, where the array holds the values of each level of the heap stored in sequence. For example level 0, the root value of the tree, is at index 0 of the array, the two values of level 1 are stored at indices 1 and 2, level 2 at the next 4 indices, level 3 over the next 8, and so on. In this way, all the 1024 leaf nodes of 2047 element heap will be stored in the final 1024 indices of the array (indices 1023 to 2046). Because you only have to compare those elements since you know the max is among them, and because you can jump straight to them using the underlying array's O(1) access by index, you only need 1023 comparisons between the final 1024 elements to find the max.

inordirection
  • 959
  • 6
  • 16
0

In min-heap consisting of 2047 elements, there are 1024 leaf nodes. In order to find the maximum element, you need n-1 comparisons. So you compare the first two elements and select the larger element and compare it with next one and so on. Therefore, the number of comparisons will be 1024-1 = 1023.

ouflak
  • 2,458
  • 10
  • 44
  • 49