码迷,mamicode.com
首页 > 编程语言 > 详细

堆排序——HeapSort

时间:2017-11-09 22:44:59      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:二次   blog   heap   ges   max   eth   sys   nlog   load   

基本思想:

技术分享
 

图示: (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

标签:二次   blog   heap   ges   max   eth   sys   nlog   load   

原文地址:http://www.cnblogs.com/diyishijian/p/7811459.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!