java堆排序

package sort;

public class HeapSort {

	public static void heapSort(int[] table) {
		//数组长度
		int n = table.length;
		
		//创建最小堆
		for (int j = n/2-1; j >= 0; j--) {
			sift(table, j, n-1);
		}
		
		//把根节点与最后一个子节点交换,然后再进行创建最小堆
		for (int j = n - 1; j > 0; j--) {
			int temp = table[0];
			table[0] = table[j];
			table[j] = temp;
			sift(table, 0, j-1);
		}
	}
	
	/**
	 * 创建最小堆
	 * @param table
	 * @param low
	 * @param high
	 */
	private static void sift(int[] table, int low, int high) {
		int i = low;
		int j = 2*i + 1;
		int temp = table[i];
		while (j <= high) {
			if (j < high && table[j] > table[j+1]) {
				j++;
			}
			if (temp > table[j]) {
				table[i] = table[j];
				i = j;
				j = 2*i + 1;
			} else {
				j = high + 1;
			}
		}
		table[i] = temp;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		int[] table = {81, 49, 76, 27, 97, 38, 49, 13, 65};
		
		heapSort(table);    //堆排序
		
		//打印
		for (int i = 0; i < table.length; i++) {
			System.out.print(table[i] + "  ");
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值