C语言版
#include <stdio.h>
#define SWAP( a, i, j ) { t = a[i]; a[i] = a[j]; a[j] = t; }
#define LESS( a, b ) ( a < b )
void disp_array( int a[], int n )
{
int i;
for( i = 0; i < n; ++i )
printf( "%d ", a[i] );
printf( "\n" );
}
void heap_adjust( int a[], int s, int m )
{
int i, key = a[s];
for( i = 2 * s + 1; i <= m; i <<= 1 )
{
if( i < m && LESS( a[i], a[i + 1] ) ) ++i;
if( ! LESS( key, a[i] ) ) break;
a[s] = a[i]; s = i;
}
a[s] = key;
}
void heap_sort( int a[], int n )
{
int i, t;
// adjust a[0...n-1] into a max heap
for( i = ( n - 2 ) / 2; i >= 0; --i )
heap_adjust( a, i, n - 1 );
printf( "Heap: " );
disp_array( a, n );
for( i = n - 1; i > 0; --i )
{
SWAP( a, 0, i );
heap_adjust( a, 0, i - 1 );
}
}
int main()
{
//int a[] = { 49, 38, 65, 97, 76, 13, 27, 49 };
int a[] = { 100, 49, 38, 65, 97, 76, 13, 27, 49 };
int n = 9;
printf( "Before sorting: " );
disp_array( a, n );
heap_sort( a, n );
printf( "After sorting: " );
disp_array( a, n );
return 0;
}
Java语言版
public class TestSort {
public static void dispArray( int a[] ) {
for( int i = 0; i < a.length; ++i )
System.out.print( a[i] + " " );
System.out.println();
}
public static void swap( int a[], int i, int j ) {
int t = a[i]; a[i] = a[j]; a[j] = t;
}
private static boolean less( int a[], int i, int j ) {
return a[i] < a[j];
}
private static boolean less( int a, int b ) {
return a < b;
}
/*
* heap sort
*/
private static void adjustHeap( int [] a, int s, int m ) {
int key = a[s];
for( int i = 2 * s + 1; i <= m; i *= 2 ) {
if( i < m && less( a[i], a[i + 1] ) ) ++i;
if( ! less( key, a[i] ) ) break;
a[s] = a[i]; s = i;
}
a[s] = key;
}
public static void heapSort( int [] a ) {
int n = a.length;
for( int i = ( n - 2 ) / 2; i >= 0; --i )
adjustHeap( a, i, n - 1 );
for( int i = n - 1; i > 0; --i ) {
swap( a, 0, i );
adjustHeap( a, 0, i - 1 );
}
}
public static void main( String[] args ) {
int a[] = { 100, 49, 38, 65, 97, 76, 13, 27, 49 };
System.out.print( "Before sorting: " );
dispArray( a );
heapSort( a );
System.out.print( "Heap sorting: " );
dispArray( a );
}
}