leetcode912 - 手撕快速排序

/**
 * @param {number[]} nums
 * @return {number[]}
 */
function qsort(arr, left, right){
    let i = left;
    let j = right;
    let base = arr[i];
    if(left >= right){
        return;
    } else {
        while (i<j){
            while(arr[j]>base && i<j){//这两个的顺序都不能错;
                j--;
            }
            while(arr[i]<=base && i<j){
                i++;
            }
            if(i<j){
                let tmp = arr[j];
                arr[j]=arr[i];
                arr[i]=tmp;
            }
        }
        arr[left]=arr[i];
        arr[i] = base;
        qsort(arr,left,i-1);
        qsort(arr,i+1,right);
    }
}

var sortArray = function(nums) {
    qsort(nums,0,nums.length-1);
    return nums;
};

 

posted @ 2021-05-09 02:37  KYSpring  阅读(58)  评论(0编辑  收藏  举报