堆排序算法(C & Java 实现)

55 篇文章 0 订阅
37 篇文章 0 订阅

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 );
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值