Java下的堆排序实现

public class SortTest {
    public static void main(String[] args) {
        int[] arr = new int[]{54, 78, 9, 90, 34, 79, 12};
        heapSort(arr, arr.length);
        System.out.println(Arrays.toString(arr));
    }

    public static void adjust(int[] arr, int start, int end) {
        int tmp = arr[start];
        int parent = start;
        for (int left = parent * 2 + 1; left < end; left = left * 2 + 1) {
            if (left < end && arr[left] < arr[left + 1]) {
                left = left + 1;
            }
            if (tmp < arr[left]) {
                arr[parent] = arr[left];
                parent = left;
            } else {
                break;
            }
        }
        arr[parent] = tmp;
    }

    public static void heapSort(int[] arr, int length) {
        int start = (length - 2) / 2;
        for (; start >= 0; start--) {
            adjust(arr, start, length - 1);
        }

        if (length - 1 > 0) {//递归实现
            int tmp = arr[length - 1];
            arr[length - 1] = arr[0];
            arr[0] = tmp;
            heapSort(arr, length - 1);
        }

        /*for(int i = 0;i < arr.length-1; i++){//非递归实现
            int tmp = arr[0];
            arr[0] = arr[arr.length-1-i];
            arr[arr.length-1-i] = tmp;
            adjust(arr,0,arr.length-1-i-1);
        }*/

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值