基本思路
1.先取数组中间的数作为比较的基准
2.定义两个数组,一个left,一个right,利用for循环遍历数组,将比基准小的数放置left数组中,反之放入right数组
3.拼接数组,返回数组,排序完成
<script>
const quickSort = arr => {
//数组元素等于小于1就没必要排序,直接return
if(arr.length<=1){
return arr;
}
//找到基准的索引
const Index = Math.floor(arr.length/2);
//把基准的索引从原数组里面删除,并且赋值给新的数组
const IndexVal = arr.splice(Index,1)[0];
//定义左右数组
const left = [];
const right = [];
//循环剩余的数组元素,将小于基准的元素添加到left,反之给right
for(let i=0;i<arr.length;i++){
if(arr[i]<IndexVal){
left.push(arr[i]);
}
else{
right.push(arr[i]);
}
}
//拼接数组,返回数组,排序完成
return quickSort(left).concat(IndexVal,quickSort(right));
}
const array = [5,4,3,2,1];
console.log(quickSort(array));
//[1,2,3,4,5]
</script>