# 堆排序(Heapsort)之Java实现

## 堆排序算法Java实现

public 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;
}
}

1. 构建最大堆。
2. 选择顶，并与第0位置元素交换
3. 由于步骤2的的交换可能破环了最大堆的性质，第0不再是最大元素，需要调用maxHeap调整堆(沉降法)，如果需要重复步骤2

public class HeapSort {
public static void main(String[] args) {
int[] array = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3 };

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);
}
}
}