美文网首页node
Node.js快速排序

Node.js快速排序

作者: zhaoolee | 来源:发表于2022-02-24 12:34 被阅读0次

    题目 https://leetcode-cn.com/problems/sort-an-array

    /**
     * @param {number[]} nums
     * @return {number[]}
     */
    var sortArray = function (nums) {
    
        function quickSort(slow, fast) {
    
    
            // 1. 选择第一个元素作为基准, 并将第一个位置设置void 0
    
            let base = nums[slow];
            nums[slow] = void 0;
    
    
            // 2. 设置两个指针,left 为 slow索引, right 为fast 索引
            let left = slow;
            let right = fast;
    
            // 3. 如果left < rigth 则不断循环排序, 如果left === right, 则停止排序
    
            while (left < right) {
    
                if (nums[left] === void 0) {
                    // 3.1 从right指针开始,如果right指向的值小于等于base, 
                    // 则 left 接收right的值,right节点设置为空,left加1
                    if (nums[right] < base) {
                        nums[left] = nums[right];
                        nums[right] = void 0;
                        left = left + 1;
                    }
                    // 如果right指针指向的值,大于等于base, 则,rigth - 1
                    else {
                        right = right - 1;
                    }
                } else if (nums[right] === void 0) {
                    if (nums[left] >= base) {
                        nums[right] = nums[left];
                        nums[left] = void 0;
                        right = right - 1;
                    }
                    else {
                        left = left + 1;
                    }
                } else {
                    console.log("不可达")
                }
            }
            // 将base放入left和rigth重合的位置
            nums[left] = base;
    
            // 如果base左侧区域差值大于等于1,则开始递归调用
    
            if ((left - 1) - slow > 0) {
                quickSort(slow, left - 1);
            }
    
            // 如果base右侧区域差值大于1,则开始递归调用
            if (fast - (right + 1) > 0) {
                quickSort(right + 1, fast);
            }
    
    
            return
    
    
        }
    
        if (nums.length === 1) {
            return nums;
        } else {
            quickSort(0, nums.length - 1);
        }
        return nums;
    
    };
    
    leetcode

    相关文章

      网友评论

        本文标题:Node.js快速排序

        本文链接:https://www.haomeiwen.com/subject/cbyzlrtx.html