Processing math: 100%

Building a Heap solved by 891

Feb. 21, 2014, 4:23 p.m. by Rosalind Team

Topics: Sorting

Problem

A binary heap is a binary tree based data structure that is often used to implement priority queues. Binary heaps, in turn, can be easily implemented using an array if the underlying tree is a complete binary tree. The tree nodes have a natural ordering: row by row, starting at the root and moving left to right within each row. If there are n nodes, this ordering specifies their positions 1,2,,n within the array. Moving up and down the tree is easily simulated on the array, using the fact that node number j has parent j/2 and children 2j and 2j+1.

The goal of this problem is to build a heap from the given array. For this, go from the end to the beginning of a given array and let each element "bubble up".

Source: Algorithms by Dasgupta, Papadimitriou, Vazirani. McGraw-Hill. 2006.

Given: A positive integer n105 and array A[1..n] of integers from 105 to 105.

Return: A permuted array A satisfying the binary max heap property: for any 2in, A[i/2]A[i].

Sample Dataset

5
1 3 5 7 2

Sample Output

7 5 1 3 2

Running timeclick to expand

Since each "bubble up" operation requires only O(logn) time the running time of this algorithm is O(nlogn). A more careful analysis shows that the running time is in fact just linear.

Please login to solve this problem.