Talk:Heap sort.c

Unknown Date: I tried to sort with this implementation and I had the result like this: Input: 1 2 3 4 5 Sorted: 1 2 5 3 4

In line 3 of the heapSort function I edited the loop initialization from for (i = (array_size / 2)-1; i >= 0; i--) to for (i = array_size - 1; i >= 0; i--) And now it works!

11-Jun-2010: I had a similar problem, but discovered my real problem was with the way I was reading my input array from a file. Changing the first for loop initialization to effectively run sortDown twice as many times shouldn't really affect anything except the time complexity for this implementation.

The array to be sorted must be one based, not zero based, i.e. the root must have index = 1. You are identifying 2*i and 2*i+1 as the left and right children of node i, but if i==0 then the left child has index 0 and the right child has index 1. Obviously that is wrong.

This implementation is seriously flawed and should be rewritten to sort an array using indexes 1..N instead of 0..N-1.