[路飞] 912. 排序数组

104 阅读1分钟

题目描述

给你一个整数数组 nums,请你将该数组升序排列。

解题思路

算法

快速排序

解题思路

是很简单的一道题,但是我们要对快排进行一个优化

空间优化

减少递归

  • 最多把数组划分到 length 为 16,不会再往下划分,剩下的部分我们靠插入排序搞定有序化
  • 只对当前划分后的右半部分进行递归 partition,而左半部分通过递归划分

时间优化

  • 通过插入排序来把长度为 <= 16 的数组区间进行排序

代码

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortArray = function (nums) {
    quickSort(nums, 0, nums.length - 1)

    return nums
};

function quickSort(nums, l, r) {
    partition(nums, l, r)
    insertSort(nums, l, r)
}

function partition(nums, l, r) {
    while (r - l > 16) {
        let x = l, y = r, base = getMid(nums[l], nums[r], nums[Math.floor((l + r) / 2)])

        do {
            while (x < y && nums[x] < base) x++
            while (x < y && nums[y] > base) y--

            if (x < y) {
                ;[nums[x], nums[y]] = [nums[y], nums[x]]
                x++
                y--
            }
        } while (x < y)

        partition(nums, x + 1, r)
        r = x
    }
}

function insertSort(nums, l, r) {
    let ind = l

    for (let i = l; i <= r; i++) {
        if (nums[ind] > nums[i]) ind = i
    }

    while (ind > l) {
        ;[nums[ind - 1], nums[ind]] = [nums[ind], nums[ind - 1]]
        ind--
    }

    for (let i = l + 2; i <= r; i++) {
        let j = i

        while (nums[j] < nums[j - 1]) {
            ;[nums[j], nums[j - 1]] = [nums[j - 1], nums[j]]
            j--
        }
    }
}

function getMid(a, b, c) {
    if (a > b) return getMid(b, a, c)
    if (a > c) return getMid(c, b, a)
    if (b > c) return getMid(a, c, b)

    return b
}