递归思路

以某某为基准

想象你是体育委员
你面对的同学为[12,3,7,21,5,9,4,6]
以某某为基准,小的去前面,大的去后面
只需要重复这句话,就能排序
image.png

快排源码

阮一峰的版本

  1. let quickSort = (arr) => {
  2. if(arr.length <= 1){return arr}
  3. let pivotIndex = Math.floor(arr.length / 2)
  4. //向下取整找中间数为基准
  5. let pivot = arr.splice(pivotIndex,1)[0];
  6. //把基准单独抽出来
  7. let left = []
  8. let right = []
  9. for(let i = 0; i < arr.length; i++){
  10. if(arr[i] < pivot){
  11. left.push(arr[i])
  12. }else{
  13. right.push(arr[i])
  14. }
  15. }
  16. return quickSort(left).concat([pivot],quickSort(right))
  17. //将左边的数组、基准、右边的数组拼起来
  18. }

image.png