javascript快速排序

时间:2024-06-08 23:35:02
function quickSort(arr){
if(arr.length <= 1) return arr;//判断是否有效数组
var cut = Math.floor(arr.length/2);//取中间下标
var left = [],right = [];
var num = arr.splice(cut,1)[0];//取基准值
for(var i = 0;i < arr.length;i ++){
if(arr[i] < num){
left.push(arr[i]);//小的放左边
}else {
right.push(arr[i]);//大的放右边
}
}
return quickSort(left).concat(num,quickSort(right));//递归
}