Tuesday, 19 July 2011

Heap Sort.


void heapsort( int a[], unsigned int n )
{
int i,temp;
for( i=n/2; i>=0; i-- )      /* build_heap */
shift_down (a, i, n-1 );
for( i=n; i>=1; i-- )
{
temp=a[0];
a[0]=a[i];
a[i]=temp;    /* delete_max */
shift_down( a, 0, i-1 );
}
}
void shift_down( int a[], unsigned int i, unsigned int n )
{
unsigned int child;
int tmp;
for( tmp=a[i]; i*2<=n; i=i*2 )
{
child = i;
if( ( child != n ) && ( a[child+1] > a[child] ) )
child++;
if( tmp < a[child] )
a[i] = a[child];
else
break;
}
a[i] = tmp;
}

No comments:

Post a Comment