堆排序(Heap-Sort)
(二叉)堆是一个数组,它可以被看成一颗近似的完全二叉树。树上的每个节点对应数组中一个元素。除了最底层外,该树是完全充满的,而且是从左向右填充的。堆排序是一种用堆来实现的排序算法,它的时间复杂度为O(nlgn),下面是堆排序的Java实现:
import java.util.Arrays;
/**
* Created by CvShrimp on 2017/10/11.
*/
public class HeapSort {
public static void maxHeap(int[] heap, int i, int endIndex) {
int selfIndex = i - 1;
int largest = selfIndex;
int leftChildIndex = 2 * i - 1;
int rightChildIndex = 2 * i;
if(leftChildIndex <= endIndex && heap[leftChildIndex] > heap[selfIndex]) {
largest = leftChildIndex;
}
if(rightChildIndex <= endIndex && heap[rightChildIndex] > heap[largest]) {
largest = rightChildIndex;
}
if(largest != selfIndex) {
swapHeapElement(heap, selfIndex, largest);
maxHeap(heap, largest + 1, endIndex);
}
}
public static void buildMaxHeap(int[] heap) {
int startIndex = heap.length/2 - 1;
for(int i = startIndex; i >= 0; i--) {
maxHeap(heap, i + 1, heap.length - 1);
}
}
public static void heapSort(int[] heap) {
//构建最大堆,最大的元素在树的根节点
buildMaxHeap(heap);
int maxIndex = heap.length - 1;
for(int i = maxIndex; i >= 0;) {
//最大的元素和最后一个元素互换位置
swapHeapElement(heap, 0, i);
i--;
//对剩下的前i+1个元素,再构建最大堆
maxHeap(heap, 1, i);
}
}
public static void swapHeapElement(int[] heap, int i, int j) {
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
public static void main(String[] args) {
int[] heap = {1,5,6,3,4,10,7,66,666,66};
HeapSort.heapSort(heap);
System.out.print("Sorted heap: ");
System.out.print(Arrays.toString(heap));
}
}