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

归并排序 #42

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

归并排序 #42

Geekhyt opened this issue Feb 26, 2021 · 0 comments

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 26, 2021

分治法典型应用,分治算法思想很大程度上是基于递归的,也比较适合用递归来实现。

处理过程是由下到上的,先处理子问题,然后再合并。

如果感觉自己对递归掌握的还不是很透彻的同学,可以移步我的这篇专栏你真的懂递归吗?

顾名思义,分而治之。一般分为以下三个过程:

  1. 分解:将原问题分解成一系列子问题。
  2. 解决:递归求解各个子问题,若子问题足够小,则直接求解。
  3. 合并:将子问题的结果合并成原问题。

归并排序就是将待排序数组不断二分为规模更小的子问题处理,再将处理好的子问题合并起来,这样整个数组就都有序了。

const mergeSort = function(arr) {
    const merge = (right, left) => {
    const result = []
    let i = 0, j = 0
    while (i < left.length && j < right.length) {
      if (left[i] < right[j]) {
        result.push(left[i++])
      } else {
        result.push(right[j++])
      }
    }
    while (i < left.length) {
      result.push(left[i++])
    }
    while (j < right.length) {
      result.push(right[j++])
    }
    return result
    }
    const sort = (arr) => {
        if (arr.length === 1) { return arr }
        const mid = Math.floor(arr.length / 2)
        const left = arr.slice(0, mid)
        const right = arr.slice(mid, arr.length)
        return merge(mergeSort(left), mergeSort(right))
    }
    return sort(arr)
}
  • 时间复杂度: O(nlogn)
  • 空间复杂度: O(n)
  • 稳定
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