The only reason I know that [-1] isn't valid is because other's (myself included) have also had this same idea in the past, and it was discussed on another forum.
You may certainly reserve the right to not visit my personal webpage. I'm not particularly proud of it anyway as it's very web 1.0 (if that).
Anyway, here is the relevant code from my site, converted to C:
Code:
#define T int
void HeapSortDownHeap(T a[], int l, int r) {
T tempItem = a[l];
int child = (l<<1) + 1;
while (child < r) {
//use right child if it is bigger
if ((child + 1 < r) && (a[child] < a[child + 1]))
++child;
if (!(tempItem < a[child]))
break;
a[l] = a[child];
l = child;
child = (child<<1) + 1;
}
a[l] = tempItem;
}
void HeapSort(T a[], int n) {
//build heap
for (int i = n>>1; i >= 0; --i)
HeapSortDownHeap(a, i, n);
//extract max item successively
for (int j = n-1; j > 0; --j) {
Swap(a[0], a[j]);
HeapSortDownHeap(a, 0, j);
}
}
As you can see, it performs just one extra addition per loop iteration inside HeapSortDownHeap. Feel free to critique the code, by the way.
You'd be hard pressed to measure any performance difference in doing it by using [-1], and if it were ever a matter of performance, you'd switch algorithm.
Nice ASCII art btw!