堆排序Heap_Sort

堆排序就是借助二叉堆进行排序,不了解二叉堆的可以先看这里。本文以升序排序为例,首先将待排序数组放置在最小堆中,此时堆顶一定是数组中最小的元素,然后删除堆顶元素,此时调整后的最小堆顶会是第二小的元素,从而实现排序。

时间复杂度:O(nlogn)

代码:

    public static  void main(String [] args) {
        Heap<Integer> h = new Heap<>();
        Integer[] i = {20,30,90,40,70,110,60,10,100,50,80};
        for (int j = 0; j < i.length; j++) {
            h.insert(i[j]);
        }
         while(!h.isEmpty())
         {
             System.out.print(h.getFirst()+" ");
             h.deleteFirst();
         }

    }

输出结果:

10 20 30 40 50 60 70 80 90 100 110

猜你喜欢

转载自www.cnblogs.com/lbrs/p/11925163.html
今日推荐