一、原理

​ 堆排序是采用数据结构堆进行排序的算法。堆是一种近似完全二叉树的结构,并同时满足堆的性质:子节点的键值或索引总是小于(或大于)它的父节点。

​ 堆中定义以下几种操作:

​ 1) 最大堆调整(Max Heapify):将堆的末端子节点作调整,使得子节点永远小于父节点 。

​ 2) 创建最大堆(Build Max Heap):将堆中的所有数据重新排序 。

​ 3) 堆排序(HeapSort):移除位在第一个数据的根节点,并做最大堆调整的递归运算。

二、代码实现

package com.jdk8.SortTest;

import java.util.Arrays;

public class Heapsort {
    public static void main(String[] args){
        int[] arrays = new int[]{1,3,2,9,8,7,6,0,4,5,10};
        System.out.println("排序前序列为:" + Arrays.toString(arrays));
        heapOperateSort(arrays);
        System.out.println("排序后序列为:" + Arrays.toString(arrays));
    }

    private static void heapOperateSort(int[] arrays) {

        int i,temp;

        for(i = (arrays.length - 2)/2;i >= 0;i--){
            downSort(arrays,i,arrays.length);
        }

        for(i = arrays.length - 1;i > 0;i-- ){
            temp = arrays[i];
            arrays[i] = arrays[0];
            arrays[0] = temp;

            downSort(arrays,0,i);
        }

    }

    private static void downSort(int[] arrays, int parentIndex, int length) {
        int temp = arrays[parentIndex];
        int childIndex = 2 * parentIndex + 1;
        while(childIndex < length){
            if((childIndex + 1)<length && arrays[childIndex + 1] > arrays[childIndex]){
                childIndex = childIndex + 1;
            }

            if(temp > arrays[childIndex]){
                break;
            }

            arrays[parentIndex] = arrays[childIndex];
            parentIndex = childIndex;
            childIndex = 2 * childIndex + 1;
        }

        arrays[parentIndex] = temp;

    }
}

三、复杂度分析

3.1、时间复杂度分析

​ 下沉调整的最坏时间复杂度相当于二叉堆的高度,即O(logn)。

​ 如上程序所示,堆排序算法分为两步,第一步生成二叉堆,第二步循环删除头元素(即堆顶元素),将其放到尾部,调节堆产生新的堆顶。

​ 第一步,生成二叉堆,进行(n-2)/2次循环,即调用(n-2)/2次downSort方法,即(n-2)/2 * O(logn)等于O(nlogn)。

​ 第二步,按程序中示,n-1次循环,即(n-1)次downSort方法,即(n-1)* O(logn),等于O(nlogn)。

​ 第一步和第二部是顺序关系,即相加关系,因此堆排序的时间复杂度是O(nlogn)。

3.2、空间复杂度

​ 堆排序的临时变量所占用的空间不随处理数据n的大小改变而改变,即空间复杂度为O(1)。

四、稳定性

​ 堆排序是不稳定排序。

posted on 2019-02-26 23:53  IT-飞鹰  阅读(138)  评论(0编辑  收藏  举报