发现本周最受开发者欢迎的代码片段,跟上技术潮流
JavaScript实现的快速排序算法
function quickSort(arr) {
if (arr.length <= 1) return arr;
const pivot = arr[0];
const left = [];
const right = [];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
// 示例
const numbers = [64, 34, 25, 12, 22, 11, 90];
console.log(quickSort(numbers));