package com.algorithm.sort;
import java.util.Arrays;
/**
* Created by louis on 2015/3/17.
*/
public class HeapSort {
private static int heapSize=0;
public static void maxHeapify(int[] arr, int i) {
int l = 2 * i; // left node
int r = 2 * i + 1; // right node
int max = i;
if (l <= heapSize && arr[l] > arr[i]) {
max = l;
}
if (r <= heapSize && arr[r] > arr[max]) {
max = r;
}
if (max != i) {
swap(arr, max, i);
maxHeapify(arr, max);
}
}
public static void buildMaxHeap(int[] arr) {
heapSize= arr.length-1;
for (int i = heapSize / 2; i >= 0; i--) {
maxHeapify(arr, i);
}
}
public static void heapSort(int[] arr) {
buildMaxHeap(arr);
for (int i = heapSize; i >= 0; i--) {
swap(arr, 0, i);
--heapSize;
maxHeapify(arr, 0);
System.out.println(String.format("step %d: %s",i,Arrays.toString(arr)));
}
}
public static void swap(int[] data, int i, int j) {
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
public static void main(String[] args) {
int[] arr = {7, 11, 3, 4, 9, 2, 18, 1};
heapSort(arr);
System.out.println(Arrays.toString(arr));
}
}
堆排序
最新推荐文章于 2024-09-04 23:05:17 发布