Hello, by searching explanations and code for heap sort I found tghis code:
#include <stdio.h>
#define less(a, b) ((a) < (b))
static void exchange ( int *a, int *b )
{
int t = *a;
*a = *b;
*b = t;
}
static void fixDown ( int *a, int k, int N )
{
int j;
while ( 2 * k <= N ) {
j = 2 * k;
if ( j < N && less ( a[j], a[j+1] ) )
j++;
if ( !less ( a[k], a[j] ) )
break;
exchange ( &a[k], &a[j] );
k = j;
}
/* Look at here*/
for (j = 0; j<10; j++)
printf ("%d ",a[j]);/* first element is -858993460*/
printf("\n");
}
static void heapsort ( int *a, int l, int r )
{
int k, N = r - l + 1;
int *pq = a + l - 1;
for ( k = N / 2; k >= 1; k-- )
fixDown ( pq, k, N );
while ( N > 1 ) {
exchange ( &pq[1], &pq[N] );
fixDown ( pq, 1, --N );
}
}
int main ( void )
{
int i;
int a[10] = {8,3,9,1,0,5,9,3,6,4};
heapsort ( a, 0, 9 );
printf("\n");
for ( i = 0; i < 10; i++ )
printf ( "%d ", a[i] );
printf ( "\n" );
return 0;
}
I think Narue wrote it on another forum. I wanted to see how fix down works and I decided to print array elements each time fixdown function is called. but when I use for loop like in the code a[0] is some garbage value, but when I put j = 1 and loop end condition to j <=10, everthing seems OK, but, if I'm not wrong that means that array boundary is passed and that is potential run time error.
Can anyone comment this and explain if this code passing beyond array bounds or not?
Thanks