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

快速排序算法 #28

Open
incuisting opened this issue Sep 7, 2017 · 0 comments
Open

快速排序算法 #28

incuisting opened this issue Sep 7, 2017 · 0 comments
Labels

Comments

@incuisting
Copy link
Owner

思路:
一共有三个步骤:

  1. 在数据集中选择一个元素作为基准数
  2. 然后将所有小于基准的数 放到数组左边,将比基准大的放在右边
  3. 对基准左边和右边的数 重复第一第二步,直到所有子集里只剩下一个元素

举个例子,现在有一个数据集{85, 24, 63, 45, 17, 31, 96, 50}。
第一步、选择中间的元素45作为"基准"。(基准值可以任意选择,但是选择中间的值比较容易理解。)

Paste_Image.png

第二步,按照顺序,将每个元素与"基准"进行比较,形成两个子集,一个"小于45",另一个"大于等于45"。

Paste_Image.png

第三步,对两个子集不断重复第一步和第二步,直到所有子集只剩下一个元素为止。

Paste_Image.png

Paste_Image.png

Paste_Image.png

Paste_Image.png

用JavaScript实现上面的思路
首先声明一个函数,名字随意,这里我们叫quickSort

var quickSort = function(arr) {
  
}

给他设定一个判断条件,数组只有一个数,就放回该数

var quickSort = function(arr) {
  if (arr.length <= 1) { return arr; }
}

接着,选择"基准"(pivot),并将其与原数组分离,再定义两个空数组,用来存放一左一右的两个子集。

var quickSort = function(arr) {
  if (arr.length <= 1) { return arr; }
  var pivotIndex = Math.floor(arr.length / 2) ;//数组对半
  var pivot = arr.splice(pivotIndex, 1)[0];
  var left = [];
  var right = [];
};

然后,开始遍历数组,小于"基准"的元素放入左边的子集,大于基准的元素放入右边的子集。

var quickSort = function(arr) {
  if (arr.length <= 1) { return arr; }
  var pivotIndex = Math.floor(arr.length / 2) ;
  var pivot = arr.splice(pivotIndex, 1)[0];
  var left = [];
  var right = [];
  for (var i = 0; i < arr.length; i++){
    if (arr[i] < pivot) {
      left.push(arr[i]);
    } else {
      right.push(arr[i]);
    }
  }
};

最后,使用递归不断重复这个过程,就可以得到排序后的数组。

var quickSort = function(arr) {
  if (arr.length <= 1) { return arr; }
  var pivotIndex = Math.floor(arr.length / 2);
  var pivot = arr.splice(pivotIndex, 1)[0];
  var left = [];
  var right = [];
  for (var i = 0; i < arr.length; i++){
    if (arr[i] < pivot) {
      left.push(arr[i]);
    } else {
      right.push(arr[i]);
    }
  }
  return quickSort(left).concat([pivot], quickSort(right));
};

最后一个递归,从递归的最后一步理解就相当于把上面的步骤图倒过来

Paste_Image.png

这个一步执行后 就拿左边那个数组来说返回数组[24,31],然后返回到上一级

Paste_Image.png

返回的[24,31]通过concat和17相连接组成一个新的数组返回。然后后面的步骤也是一次类推。最后得到

Paste_Image.png

参考:阮一峰,
array.prototype.concat

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