1. 程式人生 > >堆排序——HeapSort

堆排序——HeapSort

eat todo generate div view 排序 eap 實現 rate

基本思想:

技術分享

圖示: (88,85,83,73,72,60,57,48,42,6)

技術分享

平均時間復雜度:

O(NlogN)由於每次重新恢復堆的時間復雜度為O(logN),共N - 1次重新恢復堆操作,再加上前面建立堆時N / 2次向下調整,每次調整時間復雜度也為O(logN)。二次操作時間相加還是O(N * logN)。

Java代碼實現:

public class HeapSortTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int
[] arr = new int[] { 10, 3, 2, 5, 6, 1, -2, 3, 14, 12, 3, 8, 55, 44, -10 }; print(arr); heapSort(arr); System.out.println("排序後的數組:"); print(arr); } private static void print(int[] a) { for (int i = 0; i < a.length; i++) { System.out.print(a[i]
+ "\t"); } System.out.println(); } private static void swap(int[] a, int i, int j) { a[i] = a[i] + a[j]; a[j] = a[i] - a[j]; a[i] = a[i] - a[j]; } private static void heapSort(int[] a) { for (int i = a.length - 1; i >= 0; i--) { createMaxHeap(a, i); swap(a,
0, i); print(a); } } private static void createMaxHeap(int[] a, int lastIndex) { for (int i = (lastIndex - 1) / 2; i >= 0; i--) { int k = i; while ((2 * k + 1) <= lastIndex) { int biggerIndex = 2 * k + 1; if (biggerIndex < lastIndex) { if (a[biggerIndex] < a[biggerIndex + 1]) { biggerIndex++; } } if (a[k] < a[biggerIndex]) { swap(a, k, biggerIndex); k = biggerIndex; } else { break; } } } } }

堆排序——HeapSort