基本思路

  1. 每次排序选定一个元素为基准点(一般为中间项)
    1. 把小于基准点的所有元素放到基准点的左边数组
    2. 把大于基准点的所有元素放到基准点的右边数组
  2. 然后递归让左右两边的数组持续处理,一直到左右两边都排好序,当数组只有一项时不进行排序
  3. 最后把所有组连接一起

时间复杂度 快速排序 - 图1

  1. let quickSort = (arr) => {
  2. if(arr.length <= 1) return arr;
  3. const privotIndex = Math.floor(arr.length / 2);
  4. const privot = arr.splice(privotIndex,1)[0];
  5. const lArr = [], rArr = [];
  6. for(let i=0; i < arr.length; i++) {
  7. const item = arr[i];
  8. item < privot ? lArr.push(item) : rArr.push(item);
  9. }
  10. return quickSort(lArr).concat(privot, quickSort(rArr));
  11. }