es6快速排序

es6快速排序

let qsort = fn =>([x,...xn]) => x == null ? []
: [
...qsort(fn)(xn.filter(a=>fn(a,x))),
x,
...qsort(fn)(xn.filter(a=>!fn(a,x)))
]

 es5写法:
console.log(qsort((a,b)=>a<b)([110,765,-909,4432,-543]))
//[-909, -543, 110, 765, 4432]

 

var quickSort = function(arr) {  
if (arr.length <= 1) {
return arr;
}  
var pivotIndex = Math.floor(arr.length / 2);  
var pivot = arr.splice(pivotIndex, 1)[0];  
var left = [];  
var right = [];  
for (var 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));
};
console.log(quickSort(arr))



posted @ 2019-07-26 17:00  皓ma  阅读(2605)  评论(0编辑  收藏  举报