栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA实现堆+堆排序【数据结构·堆排序】

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA实现堆+堆排序【数据结构·堆排序】

堆是一种完全二叉树,往往用数组存储而不像其他二叉树用二叉链表存储.
下面是实现Heap类的代码

public class Heap > {
    private java.util.ArrayList list = new java.util.ArrayList<>();

    public Heap(){

    }

    public Heap(E[] objects){
        for(int i=0;i 0){
            int parentIndex = (currentIndex-1)/2;
            if(list.get(currentIndex).compareTo(
                    list.get(parentIndex) ) > 0){
                E temp = list.get(currentIndex);
                list.set(currentIndex,list.get(parentIndex));
                list.set(parentIndex,temp);
            } else {
                break;
            }
            currentIndex = parentIndex;
        }
    }

    public E remove(){
        if(list.size() == 0)
            return null;
        E removerObject = list.get(0);
        list.set(0,list.get(list.size()-1));
        list.remove(list.size()-1);

        int currentIndex = 0;
        while(currentIndex < list.size()){
            int leftChildIndex = 2*currentIndex+1;
            int rightChileIndex = 2*currentIndex+2;

            if(leftChildIndex >= list.size())
                break;
            int maxIndex = leftChildIndex;
            if(rightChileIndex < list.size()){
                if(list.get(maxIndex).compareTo(
                        list.get(rightChileIndex))<0){
                    maxIndex = rightChileIndex;
                }
            }

            if(list.get(currentIndex).compareTo(
                    list.get(maxIndex)) < 0){
                E temp = list.get(maxIndex);
                list.set(maxIndex,list.get(currentIndex));
                list.set(currentIndex,temp);
                currentIndex = maxIndex;
            } else {
                break;
            }
        }
        return removerObject;
    }

    public int getSize(){
        return list.size();
    }

}

下面是堆对数组排序的堆排序代码

public class HeapSort {
    public static > void heapSort(E[] list){
        Heap heap = new Heap<>();

        for(int i=0;i=0;i--){
            list[i] = heap.remove();
        }
    }

    //测试方法
    public static void main(String[] args) {
        Integer[] list = {-44,-5,-3,3,3,1,-4,0,1,2,4,5,53};
        heapSort(list);
        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i]+" ");
        }
    }
}

测试通过

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/673359.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号