快速排序的思路:

1、选择数组中间数作为基数,并从数组中取出此基数;

2、准备两个数组容器,遍历数组,逐个与基数比对,较小的放左边容器,较大的放右边容器;

3、递归处理两个容器的元素,并将处理后的数据与基数按大小合并成一个数组,返回。
 
代码实现:
let  arr = [85, 24, 63, 45, 17, 31, 96, 50]
function quickSort (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 (let index = 0; index < arr.length; index++) {
       if (arr[index]< pivot) {
           left.push(arr[index])
       } else {
           right.push(arr[index])
       }
  }
  return quickSort(left).concat([pivot], quickSort(right))

}
console.log(quickSort (arr))

选择数组中间数作为基数,并从数组中取出此基数;

  var pivotIndex= Math.floor(arr.length / 2)
  var pivot = arr.splice(pivotIndex, 1)[0];

准备两个数组容器,遍历数组,逐个与基数比对,较小的放左边容器,较大的放右边容器

  var left = [];
  var right = [];
  for (let index = 0; index < arr.length; index++) {
       if (arr[index]< pivot) {
           left.push(arr[index])
       } else {
           right.push(arr[index])
       }
  }

递归处理两个容器的元素,并将处理后的数据与基数按大小合并成一个数组,返回

return quickSort(left).concat([pivot], quickSort(right))

 

 

git 地址:  https://gitee.com/guangzhou110/front-end-sorting-algorithm

 

 
 
 

相关文章:

  • 2021-10-12
  • 2021-11-27
  • 2022-01-17
  • 2021-04-09
  • 2021-08-13
  • 2019-09-03
猜你喜欢
  • 2022-01-13
  • 2021-07-01
  • 2022-02-24
  • 2021-07-16
  • 2021-06-14
  • 2021-11-05
相关资源
相似解决方案