js 的排序你学会了吗?

132 阅读1分钟

前言

js 的排序方法有很多, 从简单到复杂可以有多种多样, 这里介绍常用的一些

冒泡排序

function bubbleSort3(arr) {
  let low = 0;
  let high= arr.length-1; //设置变量的初始值
  let tmp,j;
  while (low < high) {
      for (j= low; j< high; ++j) //正向冒泡,找到最大者
          if (arr[j]> arr[j+1]) {
              tmp = arr[j]; arr[j]=arr[j+1];arr[j+1]=tmp;
          }
      --high;                 //修改high值, 前移一位
      for (j=high; j>low; --j) //反向冒泡,找到最小者
          if (arr[j]<arr[j-1]) {
              tmp = arr[j]; arr[j]=arr[j-1];arr[j-1]=tmp;
          }
      ++low;                  //修改low值,后移一位
  }
  return arr;
}

console.log(bubbleSort3([2,1,5,3,8,4,9,5])) //[1, 2, 3, 4,5, 5, 8, 9]

快速排序

function quickSort(arr) {
  if (arr.length <= 1) { return arr; } // 检查数组的个数  >= 1 直接返回 
  let pivotIndex = Math.floor(arr.length / 2) ;
  let pivot = arr.splice(pivotIndex, 1)[0];
  let left = [];
  let right = [];
  // 开始遍历数组
  for(let 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));
};
const arr = [2,1,5,3,8,4,9,5]
console.log(quickSort(arr))