快速排序
const quickSort = (arr) => {
const lth = arr.length;
if (lth <= 1) {
return arr;
}
const pivotIndex = Math.floor(lth / 2);
const pivot = arr.splice(pivotIndex, 1)[0];
const left = [];
const right = [];
for (let i = 0; i < arr.length; i++) {
arr[i] < pivot ? left.push(arr[i]) : right.push(arr[i]);
}
return quickSort(left).concat([pivot], quickSort(right));
}
console.log(quickSort([1,2,6,3,5]));
网友评论