Java快速排序

 实现代码:

public static Integer[] quickSort(Integer[] arr,int low,int high){
        int i,j,temp,t;
        if(low > high){//如果低位比高位高则直接返回空
            return null;
        }
        i = low;
        j = high;
        //temp就是基准位
        temp = arr[low];
        while (i<j) {
            //先看右边,依次往左递减
            while (temp <= arr[j] && i < j) {
                j--;
            }
            //再看左边,依次往右递增
            while (temp >= arr[i] && i < j) {
                i++;
            }
            //如果满足条件则交换
            if (i < j) {
                t = arr[j];
                arr[j] = arr[i];
                arr[i] = t;
            }
        }
        //最后将基准为与i和j相等位置的数字交换
        arr[low] = arr[i];
        arr[i] = temp;
        //递归调用左半数组
        quickSort(arr, low, j-1);
        //递归调用右半数组
        quickSort(arr, j+1, high);
        return arr;
    }

测试代码及结果:

public static void main(String[] args) {
        Integer[] arr = new Integer[100];
        for(int i=0;i<100;i++){
            arr[i] = (int) (Math.random()*10000);
        }
        System.out.println("排序前:" + Arrays.toString(arr));
        System.out.println("排序后:" + Arrays.toString(quickSort(arr, 0, arr.length - 1)));
    }

排序前:[1168, 1942, 7710, 5770, 65, 1525, 5900, 1924, 8725, 4555, 5350, 9407, 9852, 960, 3997, 8156, 2026, 4950, 1198, 7400, 3777, 4293, 9269, 9838, 725, 3150, 6701, 8148, 1889, 3566, 8158, 9398, 2462, 8012, 5283, 4145, 9504, 2956, 4054, 3476, 3809, 1338, 8987, 9059, 5967, 37, 1835, 8388, 7101, 6939, 2574, 9854, 5113, 1074, 3493, 9991, 5389, 8410, 2940, 8332, 882, 5372, 3929, 3646, 222, 1935, 4195, 9047, 4094, 6214, 8529, 2423, 9518, 2881, 1261, 2971, 8828, 8449, 6617, 4217, 5209, 7498, 7334, 8851, 9405, 5243, 7396, 942, 2926, 3497, 3067, 6655, 1446, 9055, 7458, 5463, 8422, 5794, 7826, 32]
排序后:[32, 37, 65, 222, 725, 882, 942, 960, 1074, 1168, 1198, 1261, 1338, 1446, 1525, 1835, 1889, 1924, 1935, 1942, 2026, 2423, 2462, 2574, 2881, 2926, 2940, 2956, 2971, 3067, 3150, 3476, 3493, 3497, 3566, 3646, 3777, 3809, 3929, 3997, 4054, 4094, 4145, 4195, 4217, 4293, 4555, 4950, 5113, 5209, 5243, 5283, 5350, 5372, 5389, 5463, 5770, 5794, 5900, 5967, 6214, 6617, 6655, 6701, 6939, 7101, 7334, 7396, 7400, 7458, 7498, 7710, 7826, 8012, 8148, 8156, 8158, 8332, 8388, 8410, 8422, 8449, 8529, 8725, 8828, 8851, 8987, 9047, 9055, 9059, 9269, 9398, 9405, 9407, 9504, 9518, 9838, 9852, 9854, 9991]
PS:注意传参应传0和数组长度-1,否则排序只会排两个参数中间的数字,至于原因暂未可知,如有大神知道欢迎指教~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值