public class HeapSort {
static class ArrayUtils {
public static void printArray(int[] array) {
System.out.print("{");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
if (i < array.length - 1) {
System.out.print(", ");
}
}
System.out.println("}");
}
public static void exchangeElements(int[] array, int index1, int index2) {
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
}
public static void main(String[] args) {
int[] array = { 9, 8, 13, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, 12, 11, 15, 14 };
System.out.println("Before heap:");
ArrayUtils.printArray(array);
heapSort(array);
System.out.println("After heap sort:");
ArrayUtils.printArray(array);
}
public static void heapSort(int[] array) {
// if (array == null || array.length <= 1) {
// return;
// }
buildMaxHeap(array);
for (int i = array.length - 1; i >= 1; i--) {
ArrayUtils.exchangeElements(array, 0, i);
maxHeap(array, i, 0);
}
}
private static void buildMaxHeap(int[] array) {
// if (array == null || array.length <= 1) {
// return;
// }
int half = (array.length) / 2;
for (int i = half; i >= 0; i--) {
maxHeap(array, array.length, i);
}
}
// 堆调整,使其生成最大堆
private static void maxHeap(int[] array, int heapSize, int index) {
int left = index * 2 + 1;// 左子节点索引
int right = index * 2 + 2;// 右子节点索引
int largest = index;// 最大节点索引
// 如果左子节点大于父节点,则将左子节点作为最大节点
if (left < heapSize && array[left] > array[index]) {
largest = left;
}
// 如果右子节点比最大节点还大,那么最大节点应该是右子节点
if (right < heapSize && array[right] > array[largest]) {
largest = right;
}
// 最后,如果最大节点和父节点不一致,则交换他们的值
if (index != largest) {
ArrayUtils.exchangeElements(array, index, largest);
// 交换完父节点和子节点的值,对换了值的子节点检查是否符合最大堆的特性
maxHeap(array, heapSize, largest);
}
ArrayUtils.printArray(array);
}
public static void maxHeaps(int[] array,int heapSize,int index){
if(array==null || array.length<=1){
return;
}
int left = 2*index+1;
int right = 2*index+2;
int largest = index;
if(left<heapSize && array[left]>array[index]){
largest=left;
}
if(right<heapSize && array[right]>array[largest]){
largest=right;
}
if(index!=largest){
ArrayUtils.exchangeElements(array, index, largest);
maxHeaps(array, heapSize, largest);
}
}
}
排序 堆排序
最新推荐文章于 2021-07-17 11:22:45 发布