快速排序精简版

class Solution {
    //快速排序
    public int[] sortArray(int[] nums) {
        quickSort(nums,0,nums.length-1);
        return nums;
    }
    private void quickSort(int[] nums,int low,int high){
        int i = low,j = high,temp;
        if(i > j) return;  //注意此处有坑 递归出口要放在前面
        temp = nums[low];  //注意基准元素在执行完上面判断后在赋值 不然越界

        while(i < j){
            //注意先j-- 在i++ 这样保证i == j 时上面while循环结束
            //后nums[i]位置的元素是比基准小的 后面方便交换
            while(temp <= nums[j] && i < j) j--;
            while(temp >= nums[i] && i < j) i++;
            if(i < j) swap(nums,i,j);
        }
        //交换基准元素和i j重合的元素  这样基准元素就在中间了 
        //左边是比他小的 右边是比它大的
        swap(nums,low,i);

        //递归调用左边和右边
        quickSort(nums,low,j-1);
        quickSort(nums,j+1,high);
    }
    //数组元素交换函数
    private void swap(int[] nums, int index1, int index2) {
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }
}
posted @ 2021-07-16 07:29  一点尘尘  阅读(95)  评论(0)    收藏  举报