美文网首页
常用排序算法之堆排序

常用排序算法之堆排序

作者: Andy周 | 来源:发表于2016-07-26 20:59 被阅读51次

堆排序算法

/**
     * 堆排序
     *
     * @param array
     * @return
     */
    public static int[] heapSort(int[] array) {
        int arrayLength = array.length;
        for (int i = 0; i < arrayLength - 1; i++) {
            buildMaxHeap(array, arrayLength - 1 - i);
            swap(array, 0, arrayLength - 1 - i);
        }
        return array;
    }


    private static void swap(int[] data, int i, int j) {
        int tmp = data[i];
        data[i] = data[j];
        data[j] = tmp;
    }

    private static void buildMaxHeap(int[] data, int lastIndex) {
        for (int i = (lastIndex - 1) / 2; i >= 0; i--) {
            int k = i;
            while (k * 2 + 1 <= lastIndex) {
                int biggerIndex = 2 * k + 1;
                if (biggerIndex < lastIndex) {
                    if (data[biggerIndex] < data[biggerIndex + 1]) {
                        biggerIndex++;
                    }
                }

                if (data[k] < data[biggerIndex]) {
                    swap(data, k, biggerIndex);
                    k = biggerIndex;
                } else {
                    break;
                }
            }
        }
    }

运行

/**
     * 待排序的数组
     */
    private static int[] array = {
            12, 10, 5, 9, 5, 32, 16, 1, 9, 99, 80, 3, 18, 19, 20, 25, 7, 15
    };

    public static void main(String[] args) {

        int[] result = SortUtils.heapSort(array.clone());
        System.out.println(Arrays.toString(result));

    }

输出

[1, 3, 5, 5, 7, 9, 9, 10, 12, 15, 16, 18, 19, 20, 25, 32, 80, 99]

相关文章

  • 堆排序

    转载:图解排序算法(三)之堆排序 预备知识 堆排序 堆排序是利用堆这种数据结构而设计的一种排序算法,堆排序是一种选...

  • 常用的排序算法

    常用的排序算法 常用的排序算法插入排序折半插入排序shell 排序冒泡排序选择排序快速排序基数排序归并排序堆排序K...

  • iOS算法总结-堆排序

    iOS算法总结-堆排序 iOS算法总结-堆排序

  • 3.11 堆的概念及堆排序思路

    Chapter3: 更好的查找与排序算法 11. 堆的概念及堆排序 [1] 图解排序算法(三)之堆排序 讲得很好,...

  • 3.2-选择排序-堆排序

    参考链接 选择排序:堆排序(Heap Sort) 白话经典算法系列之七 堆与堆排序 堆排序与快速排序,归并排序一样...

  • 2018-06-30

    排序算法之堆排序 堆排序是利用堆的数据结构而设计的一种排序算法,堆排序是一种选择排序。可以利用数组的特点快速定位制...

  • 常用排序算法之堆排序

    堆排序算法 运行 输出

  • 排序算法

    排序算法分类 排序算法常用主要有:冒泡排序法、快速排序法、选择排序法、插入排序法、堆排序法、归并排序法等几种。 ...

  • 排序算法-堆排序

    参考: Java排序算法(五):堆排序 【算法与数据结构】图说堆排序 【数据结构】排序算法:希尔、归并、快速、堆排...

  • 数据结构与算法

    常见排序算法 堆排序 算法大全 算法大汇总

网友评论

      本文标题:常用排序算法之堆排序

      本文链接:https://www.haomeiwen.com/subject/istojttx.html