【数据结构与算法】堆排序

  • 空间复杂度

仅使用了常数个辅助单元,空间复杂度是O(1)。

  • 时间复杂度

在最好、最坏平均情况下,堆排序的时间复杂度是O(n*log2n)。

  • 代码实现

/**
 * 源码名称:HeapSort.java 
 * 日期:2014-08-12
 * 程序功能: 堆排序 
 * 版权:CopyRight@A2BGeek 
 * 作者:A2BGeek
 */
public class HeapSort {

	public void adjustHeap(int[] in, int index, int length) {
		int leftcIndex = index * 2 + 1;
		int rightcIndex = index * 2 + 2;
		int bigest = index;
		while (leftcIndex < length || rightcIndex < length) {
			if (leftcIndex < length && in[leftcIndex] > in[bigest]) {
				bigest = leftcIndex;
			}
			if (rightcIndex < length && in[rightcIndex] > in[bigest]) {
				bigest = rightcIndex;
			}
			if (index == bigest) {
				break;
			} else {
				in[index] = in[index] + in[bigest];
				in[bigest] = in[index] - in[bigest];
				in[index] = in[index] - in[bigest];
				index = bigest;
				leftcIndex = index * 2 + 1;
				rightcIndex = index * 2 + 2;
			}
		}
	}

	public void createHeap(int[] in) {
		int length = in.length;
		for (int i = length / 2; i >= 0; i--) {
			adjustHeap(in, i, length);
			printArray(in);
		}
	}

	public void printArray(int[] in) {
		for (int i : in) {
			System.out.print(i + " ");
		}
		System.out.println();
	}

	public static void main(String[] args) {
		HeapSort heapSort = new HeapSort();
		int[] testCase = { 1, 3, 4, 2, 10, 11, 45, 6 };
		heapSort.createHeap(testCase);
		int length = testCase.length;
		while (length > 1) {
			testCase[0] = testCase[0] + testCase[length - 1];
			testCase[length - 1] = testCase[0] - testCase[length - 1];
			testCase[0] = testCase[0] - testCase[length - 1];
			heapSort.adjustHeap(testCase, 0, --length);
		}
		System.out.println("#########################");
		heapSort.printArray(testCase);
	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值