You are given an integer array with N elements. Your task is to build a max binary heap from the array.
A max-heap is a complete binary tree in which the value of each internal node is greater than or equal to the values of the children of that node.
Note :You do not need to print anything, just return the vector representation of the heap such that the input array follows 0 - based indexing and :
The left child of the ith node is at (2 * i + 1)th index.
The right child of the ith node is at (2 * i + 2)th index.
Parent of the node present at ith index is at (i - 1) / 2 indexes.
The first line of input contains a single integer T, representing the number of test cases or queries to be run.
Then the T test cases follow.
The first line of each test case contains the size of the array that is N.
The second line of each test case contains N space-separated integers representing the elements of the array.
Output Format:
For each test case, if the array returned by the function buildHeap is representing a max-heap, print ‘1’ else print ‘0’.
The output of each test case is printed in a separate line.
1 <= T <= 10
1 <= N <= 10^4
-10^9 <= data <= 10^9
1
5
4 10 3 5 1
1
One possible max-heap representation of array = 10 5 3 4 1

1
11
1 3 5 4 6 13 10 9 8 15 17
1
Arrange the elements of the array starting from last such that the array should be representing heap.
The idea is to follow a top-down approach. The given array, represents a binary tree but does not follow the property of heap, in order to convert the input array to heap array heapify the complete binary tree formed from array in reverse level order following a top-down approach. It can be observed that leaf nodes need not be heapified as they already follow the heap property. Also, the array representation of the complete binary tree contains the level order traversal of the tree.
So find the position of the last non leaf node and perform the heapify operation of each non-leaf node in reverse level order.
Algorithm:
O(N * log(N)), Where N is the number of elements in the array.
The algorithm uses heapification which is a logarithmic algorithm and thus takes log(N) time and heapification is done for all the elements of the array, so the total time complexity will be O(N*log(N)).
O(1)
Constant extra space is required.