数据结构——堆(java)

public class HeapSortTest{
    @Test
    public void test() {
        List<Integer> list = new ArrayList<>();
        for (int i = 1;i<=5;i++) {
            list.add((new Object().hashCode())%50+1);
        }
        System.out.println(list.toString());
        System.out.println(heapSortTest(list).toString());
    }
    /*
     * 对于堆排序,每次从建好的大(小)顶堆里面取出最上面的元素,和数组的最后一个交换
     * 然后数组长度减一从新建堆。循环以后,最后的得到的数组就是排序好的
     */
    public List<Integer> heapSortTest(List<Integer> a){
        for(int i = a.size();i > 1;i--){//注意边界值。updateHeap中的aNum最小值为2
            //得到大顶堆
            builtHeap(a, i);
            //swap(a[0],a[i-1])

            a.set(0,a.get(0)+a.get(i-1));
            a.set(i-1,a.get(0)-a.get(i-1));
            a.set(0,a.get(0)-a.get(i-1));
        }
        return a;
    }
    //建堆
    public void builtHeap(List<Integer> a,int aNum){
        for(int i = (aNum-1)/2; i >= 0; i--){//(aNum-1)/2 means the first not leafnode
            updateHeap(a, i, aNum);//form the bottom to built the heap,and update constantly
        }
    }
    //更新堆
    public void updateHeap(List<Integer> a,int index,int aNum){
        int l = 2*index+1;//left index
        int r = 2*index+2;//right index
        int largest = index;//root index for temp
        if(l < aNum && a.get(l) > a.get(largest)) largest = l;//firstly make sure (l,r)<a.lenth
        if(r < aNum && a.get(r) > a.get(largest)) largest = r;//max(a[l],a.[r],a.[largest])
        if(largest != index){
            //swap(a.get(largest),a.get(index))
            a.set(largest,a.get(largest)+a.get(index));
            a.set(index,a.get(largest)-a.get(index));
            a.set(largest,a.get(largest)-a.get(index));
            //交换时候,要保证左右子树依旧是堆
            updateHeap(a, largest, aNum);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值