java實現堆排序算法
public class HeapSort extends DataCrol {
private void heapify(int A[], int i, int size) { // 從A[i]向下進行堆調整
int leftChild = 2 * i + 1; // 左孩子索引
int rightChild = 2 * i + 2; // 右孩子索引
int max = i; // 選出當前結點與其左右孩子三者之中的最大值
if (leftChild < size && A[leftChild] > A[max])
max = leftChild;
if (rightChild < size && A[rightChild] > A[max])
max = rightChild;
if (max != i) {
swap(A, i, max); // 把當前結點和它的最大(直接)子節點進行交換
heapify(A, max, size); // 遞歸調用,繼續從當前結點向下進行堆調整
}
}
//建立大根堆過程
// 58 55 93 61 61 29 68 00 22 07
// i
// 58 55 93 61 61 29 68 00 22 07
// i L R
// 58 55 93 61 61 29 68 00 22 07
// i L R
// 58 55 93 61 61 29 68 00 22 07
// i L R ->swap(i,L)
// 58 61 93 55 61 29 68 00 22 07
// i L R
// 58 61 93 55 61 29 68 00 22 07
// i L R ->swap(i,R)
// 93 61 58 55 61 29 68 00 22 07
// i L R ->swap(i,R)
// 93 61 68 55 61 29 58 00 22 07
// i
private void buildHeap(int A[], int size) { // 建堆,時間複雜度O(n)
for (int i = size / 2 - 1; i >= 0; i--) // 從每一個非葉結點開始向下進行堆調整
heapify(A, i, size);
}
public void heapSortOrigin(int[] array) {
//原生實現大根堆
PriorityQueue<Integer> maxHeap = new PriorityQueue<>();
int heapSize = array.length;
for (int i = 0; i < heapSize; i++) maxHeap.offer(array[i]);
while (heapSize > 0) {
array[--heapSize] = maxHeap.poll();
}
}
@Override
public void sort(int[] array) {
int heapSize = array.length;
buildHeap(array, heapSize); // 建立一個最大堆
while (heapSize > 1) { // 堆(無序區)元素個數大於1,未完成排序
// 將堆頂元素與堆的最後一個元素互換,並從堆中去掉最後一個元素
// 此處交換操作很有可能把後面元素的穩定性打亂,所以堆排序是不穩定的排序算法
swap(array, 0, --heapSize);
heapify(array, 0, heapSize); // 從新的堆頂元素開始向下進行堆調整,時間複雜度O(logn)
}
// heapSortOrigin(array);
}
public static void main(String[] args) {
HeapSort heapSort = new HeapSort();
int[] array = DataCrol.createRandomArray(10);
DataCrol.print(array);
heapSort.sort(array);
DataCrol.print(array);
heapSort.timeTest(10000000);
}
}
log
58 55 93 61 61 29 68 0 22 7
0 7 22 29 55 58 61 61 68 93