码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-08-08 16:04:16      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:数据结构   算法   堆排序   

堆排序的时间复杂度是O(nlogn),下面上代码

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 {
				int sum = in[index] + in[bigest];
				in[bigest] = sum - in[bigest];
				in[index] = sum - 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) {
			int sum = testCase[0] + testCase[length - 1];
			testCase[0] = sum - testCase[0];
			testCase[length - 1] = sum - testCase[0];
			heapSort.adjustHeap(testCase, 0, --length);
		}
		System.out.println("#########################");
		heapSort.printArray(testCase);
	}
}


【数据结构与算法】堆排序,布布扣,bubuko.com

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

标签:数据结构   算法   堆排序   

原文地址:http://blog.csdn.net/a2bgeek/article/details/38440143

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!