排序法 | 平均时间复杂度 | 最差时间复杂度 | 空间复杂度 | 是否稳定 |
---|
堆排序 | O(n*logn) | O(n*logn) | O(1) | 不稳定 |
public class HeapSort {
private static int heapSize;
public static void main(String[] args) {
HeapSort heapSort = new HeapSort();
int[] array = {4,1,3,2,16,9,10,14,8,7};
heapSort.doHeapSort(array);
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
}
private void doHeapSort(int[] array) {
buildMaxHeap(array);
for(int i = array.length - 1; i > 0; i--) {
exchange(array, 0, i);
heapSize--;
maxHeapify(array, 0);
}
}
private void buildMaxHeap(int array[]) {
heapSize = array.length;
for(int i = array.length/2 - 1; i >= 0; i--) {
maxHeapify(array, i);
}
}
private void maxHeapify(int[] array, int index) {
int leftIndex = leftNode(index);
int rightIndex = rightNode(index);
int largest = index;
if(leftIndex < heapSize && array[leftIndex] >= array[index]) {
largest = leftIndex;
}
if(rightIndex < heapSize && array[rightIndex] >= array[largest]) {
largest = rightIndex;
}
if(largest != index) {
exchange(array, index, largest);
maxHeapify(array, largest);
}
}
private void exchange(int[] array, int i, int j) {
array[i] ^= array[j];
array[j] ^= array[i];
array[i] ^= array[j];
}
private int leftNode(int index) {
return index*2 + 1;
}
private int rightNode(int index) {
return index*2 + 2;
}
}