伪最大堆顶堆排序--没有真正理解最大堆

伪最大堆排序HeapSort:

1、在这个排序中只想到把最大的值放到堆顶,没有注意到最大堆的定义:最大堆的任意子树中的根节点不小于该子树的子节点;

public class HeapSortCopy {
    private static int num = 0;//循环次数
    
    public int[] sort(int[] forSort,int lenght){
        if (forSort == null || lenght <= 1) {  
            return forSort;  
        }
        while(lenght>1){
            for(int i=lenght/2-1;i>=0;i--){
                num++;
                int largest = i ;
                if(2*i+1<=lenght-1 && forSort[i] < forSort[2*i+1]){
                    largest = 2*i + 1;
                }
                if(2*i+2<=lenght-1 && forSort[largest] < forSort[2*i+2]){
                    largest = 2*i+2;
                }
                //System.out.println("分次结果:"+Arrays.toString(forSort) +",i="+i);
                if(largest != i) swap(forSort,i,largest);
            }
            swap(forSort,0,lenght-1);
            lenght--;
//            sort(forSort, lenght);
        }
        return forSort;
    }

    private void swap(int[] forSort,int i, int j) {
        int temp = forSort[i];
        forSort[i] = forSort[j];
        forSort[j] = temp;
    }
    
    public static void main(String[] args) {
//        int[] array = {2,5,6,8,5,4,6,9,4,9};
        int[] array = {2,5,6,8,5,4,6,9,4,9,-4,-6,45,54,67,0,8,4,-3,5,-23,-45,30};  
        HeapSortCopy heapSort = new HeapSortCopy();
        long begintime = System.currentTimeMillis();
        heapSort.sort(array, array.length);
        long endtime = System.currentTimeMillis();
        System.out.println("最终结果:"+Arrays.toString(array)+",num="+num);
                
    }
}

执行结果:

最终结果:[-45, -23, -6, -4, -3, 0, 2, 4, 4, 4, 5, 5, 5, 6, 6, 8, 8, 9, 9, 30, 45, 54, 67],num=132

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值