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

归并排序 #984

Open
pwstrick opened this issue Jul 6, 2020 · 0 comments
Open

归并排序 #984

pwstrick opened this issue Jul 6, 2020 · 0 comments
Labels
一句话算法 一句话算法系列中的代码实现

Comments

@pwstrick
Copy link
Owner

pwstrick commented Jul 6, 2020

function mergeSort(arr) {		//采用自上而下的递归方法
  var len = arr.length;
  if (len < 2) {
    return arr;
  }
  var middle = Math.floor(len / 2),
    left = arr.slice(0, middle),
    right = arr.slice(middle);
  return merge(mergeSort(left), mergeSort(right));
}

function merge(left, right) {
  var result = [];
  while (left.length && right.length) {
    if (left[0] <= right[0]) {
      result.push(left.shift());
    } else {
      result.push(right.shift());
    }
  }
  while (left.length)
    result.push(left.shift());
  while (right.length)
    result.push(right.shift());
  return result;
}
@pwstrick pwstrick added the 一句话算法 一句话算法系列中的代码实现 label Jul 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
一句话算法 一句话算法系列中的代码实现
Projects
None yet
Development

No branches or pull requests

1 participant