堆排序算法实现

堆排序算法代码实现

class HeapSort {

    public static void main(String[] args) {
        int[] src = {1, 5, 7, 2, 3, 8, 27, 19,1, 5, 7, 2, 3, 8, 27, 19,1, 5, 7, 2, 3, 8, 27, 19,1, 5, 7, 2, 3, 8, 27, 19,1, 5, 7, 2, 3, 8, 27, 19};
        heapSort(src);
        for(int num : src){
            System.out.print(num + " ");
        }

    }
    public static void heapSort(int[] nums){
        buildMaxHeap(nums,nums.length);
        for(int i = nums.length - 1; i >= 0; i--){
            swap(nums,i,0);
            buildMaxHeap(nums,i);
        }
    }
    public static void buildMaxHeap(int[] nums,int length){
        for(int i = (length - 2) / 2; i >= 0; i--){
            maxHeapfy(nums,i,length - 1);
        }
    }
    public static void maxHeapfy(int[] nums,int index,int end){

        if(index >= end){
            return;
        }
        int max = index;

        int left = index * 2 + 1;
        int right = index * 2 + 2;
        if(left <= end && nums[left] > nums[max])
            max = left;
        if(right <= end && nums[right] > nums[max])
            max = right;
        if(max != index) {
            swap(nums, index, max);
            maxHeapfy(nums, max, end);
        }

    }
    public static void swap(int[] nums,int i,int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值