function jsQuickSort(array) {
if (array.length <= 1) {
return array;
}
const pivotIndex = Math.floor(array.length / 2);
const pivot = array.splice(pivotIndex, 1)[0]; //从数组中取出我们的"基准"元素
const left = [], right = [];
array.forEach(item => {
if (item < pivot) { //left 存放比 pivot 小的元素
left.push(item);
} else { //right 存放大于或等于 pivot 的元素
right.push(item);
}
});
//至此,我们将数组分成了left和right两个部分
return jsQuickSort(left).concat(pivot, jsQuickSort(right)); //分而治之
}
const arr = [98, 42, 25, 54, 15, 3, 25, 72, 41, 10, 121];
console.log(jsQuickSort(arr)); //输出:[ 3, 10, 15, 25, 25, 41, 42, 54, 72, 98, 121 ]
JS的快排实现
最新推荐文章于 2022-04-03 23:15:05 发布