package com.wzs;
import java.util.Arrays;
/**
* 算法导论--page86
*
* @author Administrator
*
*/
public class HeapSort {
private static int[] sort = new int[] { 1, 0, 10, 20, 3, 5, 6, 4, 9, 8, 12, 17, 34, 11 };
public static void main(String[] args) {
System.out.println(Arrays.toString(sort));
buildMaxHeap(sort);
System.out.println(Arrays.toString(sort));
heapSort(sort);
System.out.println(Arrays.toString(sort));
}
/**
* 建堆
*
* @param data
*/
private static void buildMaxHeap(int[] data) {
// 没有子节点的才需要创建最大堆,从最后一个的父节点开始
int startIndex = getParentIndex(data.length - 1);
// 从尾端开始创建最大堆,每次都是正确的堆
for (int i = startIndex; i >= 0; i--) {
maxHeap(data, data.length, i);
}
}
/**
* 维护堆的性质
*
* @param data
* @param heapSize
* 需要创建最大堆的大小,一般在sort的时候用到,因为最多值放在末尾,末尾就不再归入最大堆了
* @param index
* 当前需要创建最大堆的位置
*/
private static void maxHeap(int[] data, int heapSize, int index) {
// 当前点与左右子节点比较
int left = getChildLeftIndex(index);
int right = getChildRightIndex(index);
int largest = index;
if (left < heapSize && data[index] < data[left]) {
largest = left;
}
if (right < heapSize && data[largest] < data[right]) {
largest = right;
}
// 得到最大值后可能需要交换,如果交换了,其子节点可能就不是最大堆了,需要重新调整
if (largest != index) {
exchange(data, index, largest);
maxHeap(data, heapSize, largest);
}
}
private static void exchange(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/**
* 排序,最大值放在末尾,data虽然是最大堆,在排序后就成了递增的
*
* @param data
*/
private static void heapSort(int[] data) {
// 末尾与头交换,交换后调整最大堆
for (int i = data.length - 1; i > 0; i--) {
int temp = data[0];
data[0] = data[i];
data[i] = temp;
maxHeap(data, i, 0);
}
}
/**
* 父节点位置
*
* @param current
* @return
*/
private static int getParentIndex(int current) {
return (current - 1) >> 1;
}
/**
* 左子节点position 注意括号,加法优先级更高
*
* @param current
* @return
*/
private static int getChildLeftIndex(int current) {
return (current << 1) + 1;
}
/**
* 右子节点position
*
* @param current
* @return
*/
private static int getChildRightIndex(int current) {
return (current << 1) + 2;
}
}
算法导论_堆排序
最新推荐文章于 2019-03-19 14:19:13 发布