heap sort problem

This is a discussion on heap sort problem within the C++ Programming forums, part of the General Programming Boards category; I'm trying to sort an array of numbers with heap sort, but it's not sorting the first number in the ...

I'm pretty sure the reason is because the whole sorting algorithm is made for a 1 based array (where the first position is 1, not 0). I'm pretty sure it's an easy fix, but i've been trying for a long time and can't figure it out. If I made the first position in the array a dead spot, and shifted the values one spot, this would fix the problem, but i can't figure out how.
Also, for my real program, i read the numbers in from a file ( i created the above one so it could be copied and pasted to run. The real program requires a file, and needs to be run using the command prompt, so the solution to my problem could be slightly different in each case):

The main change you need to make to make heapsort work with a zero-based array is to change the child indexing from this:

Code:

int l = i << 1;
int r = (i << 1) + 1;

to this:

Code:

int r = (i + 1) << 1;
int l = r - 1;

Otherwise you can't pass i=zero because i<<1 is still zero. With this change, the children of index zero become 1 and 2 - just what you want.
You then have to change this line:

Code:

c += MaxHeapify(array1, 1, i-1);

to this:

Code:

c += MaxHeapify(array1, 0, i-1);

and also adjust the start and end values of your decrementing for loops but one. There might be more you need to change, but you can probably figure the rest out on your own.

Oh I see you have used recursion in MaxHeapify! You definitely shouldn't do that. Yes it will work, but one noted advantage of heapsort is that it is one of the algorithms that doesn't require anything more than constant space, and your implementation uses log(n) stack space.

I also strongly suggest you make the function interfaces consistent. You should never have to pass in 'size' to some algorithms and 'size-1' to others. This parameter should always be the number of items to sort. If you have to, subtract 1 inside the start of the sorting function.

Since you seem to be interested in a number of sorting algorithms, you may want to have a look at my webpage, which contains the implementations of at least 60 array sorting algorithms, all in C++.