堆排序JAVA代码

public class HeapSort {

	/**
	 * @描述:
	 * @方法名: sortHeap
	 * @param array
	 * @param start开始位置
	 * @param end结束位置
	 * @返回类型 void
	 * @创建人 lenovo
	 * @创建时间 2016-1-16下午8:42:55
	 * @修改人 lenovo
	 * @修改时间 2016-1-16下午8:42:55
	 */
	/*堆排序技巧:从最后元素建立大根堆;(createHeapandSort前半段)
	 * 每次交换最大元素跟当前堆,同时重新排堆,堆不断减少。(createHeapandSort后半段)
	 * sortHeap是用于建堆,此时堆处于除了start开始的元素都是满足大根堆的定义的。
	*/
	public static void sortHeap(int[] array, int start, int end)// 重新排序大根堆,只有第一个元素不满足堆的定义,需要将该元素不断下移。log(n)复杂度
	{

		int k = array[start];
		int current_index = start;
		int temp;
		while (current_index <= end) {
			if (2 * current_index + 1 > end)
				break;
			else if (2 * current_index + 2 > end)
				temp = 2 * current_index + 1;// 没后续了
			else {

				if (array[2 * current_index + 1] >= array[2 * current_index + 2]) {
					temp = 2 * current_index + 1;// 取较大的
				} else {
					temp = 2 * current_index + 2;
				}
			}// 这一步是用于定义temp

			if (array[current_index] >= array[temp]) {
				break;
			} else {
				change(array, current_index, temp);
				current_index = temp;
			}
		}
	}

	private static void change(int[] array, int current_index, int temp) {
		// TODO Auto-generated method stub
		int w = array[current_index];
		array[current_index] = array[temp];
		array[temp] = w;
	}

	public static void createHeapandSort(int[] array)//先建立大根堆
	{
		for(int i=array.length-1;i>=0;i--)//倒着建堆
			sortHeap(array,i,array.length-1);
		
		for(int i=0;i<=array.length-1;i++)
		{
			change(array,0,array.length-1-i);//堆从后面越来越少了
			sortHeap(array,0,array.length-1-i-1);
		}
	}

	public static void main(String args[]) {
		int a[] = new int[] { 7,2,4,5,3,1,8,99,10,21,2123,2212,12,212};
		createHeapandSort(a);
		for (int i = 0; i <= a.length - 1; i++)
			System.out.println(a[i] + " ");
	}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值