Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

快速排序 #43

Open
Geekhyt opened this issue Feb 26, 2021 · 0 comments
Open

快速排序 #43

Geekhyt opened this issue Feb 26, 2021 · 0 comments

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 26, 2021

快速排序可视化视频

快速排序也是分治法的应用,处理过程是由上到下的,先分区,然后再处理子问题。

快速排序通过遍历数组,将待排序元素分隔成独立的两部分,一部分记录的元素均比另一部分的元素小,则可以分别对这两部分记录的元素继续进行排序,直到排序完成。

这就需要从数组中挑选出一个元素作为 基准(pivot),然后重新排序数列,将元素比基准值小的放到基准前面,比基准值大的放到基准后面。

然后将小于基准值的子数组(left)和大于基准值的子数组(right)递归地调用 quick 方法,直到排序完成。

const quickSort = function(arr) {
    const quick = function(arr) {
        if (arr.length <= 1) return arr
        const len = arr.length
        const index = Math.floor(len >> 1)
        const pivot = arr.splice(index, 1)[0]
        const left = []
        const right = []
        for (let i = 0; i < len; i++) {
            if (arr[i] > pivot) {
                right.push(arr[i])
            } else if (arr[i] <= pivot) {
                left.push(arr[i])
            }
        }
        return quick(left).concat([pivot], quick(right))
    }
    const result = quick(arr)
    return result
}
  • 时间复杂度: O(nlogn)
  • 空间复杂度: O(nlogn)
  • 不稳定
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant