This is not a homework. Just an interesting task 🙂
Given a complete binary search three represensted by array. Sort the array in O(n) using constant memory.
Example:
Tree:
8
/ \
4 12
/\ / \
2 6 10 14
/\ /\ /\ /\
1 3 5 7 9 11 13 15
Array: 8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15
Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
It is possible, people calling it homework probably haven’t tried solving it yet.
We use the following as a sub-routine:
A solution for that can be found here: http://arxiv.org/abs/0805.1598
We use that as follows.
Do the above interleaving for the first 2^(k+1) – 2 elements, starting at k=1 repeating for k=2, 3 etc, till you go past the end of array.
For example in your array we get (interleaving sets identified by brackets)
So the total time is n + n/2 + n/4 + … = O(n).
Space used is O(1).
That this works can be proved by induction.