[算法]堆排序

堆排序已经忘记的差很少了,借此回顾一下。详见百度百科
java

public class HeapSort {
	//待排序数组,第0个元素无效
	private static int[] array = {-1, 3, 1, 5, 10, 7, 8, 4};
	//数组的有效元素个数
	private static int size = array.length - 1;
	
	//交换数组的第i和第j个元素
	private void swap(int i, int j) {
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}
	
	//递归调整堆
	private void heapAdjust(int index, int heapSize) {
		int leftChildIndex = index * 2;
		int rightChildIndex = index * 2 + 1;
		int tempIndex = index;
		if (index <= heapSize / 2) {
			//大顶堆
			if (leftChildIndex <= heapSize && array[leftChildIndex] >= array[tempIndex]) {
				tempIndex = leftChildIndex;
			}
			if (rightChildIndex <= heapSize && array[rightChildIndex] >= array[tempIndex]) {
				tempIndex = rightChildIndex;
			}
			if (tempIndex != index) {
				swap(tempIndex, index);
				heapAdjust(tempIndex, heapSize); //递归调用
			}
		}
	}
	
	//建立堆
	private void buildHeap() {
		for (int i = size / 2 ; i >= 1 ; i--) {
			heapAdjust(i, size);
		}
		System.out.println("初始大顶堆:");
		for (int i : array) {
			if (i == -1) {
				continue; //-1为无效值
			}
			System.out.print(" " + i);
		}
	}
	
	//堆排序
	public void heapSort() {
		buildHeap(); //首先建立大顶堆
		for (int i = size ; i >= 1 ; i--) {
			swap(1, i);
			heapAdjust(1, i - 1);
		}
		System.out.println("完成排序:");
		for (int i : array) {
			if (i == -1) {
				continue; //-1为无效值
			}
			System.out.print(" " + i);
		}
	}
}
相关文章
相关标签/搜索