以下是使用js封装的快速排序算法:
function quickSort(arr) {
if (arr.length <= 1) {
return arr;
}
const pivotIndex = Math.floor(arr.length / 2);
const pivot = arr[pivotIndex];
const left = [];
const right = [];
for (let i = 0; i < arr.length; i++) {
if (i === pivotIndex) continue;
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
使用方法:
const arr = [3, 1, 4, 2, 5];
const sortedArr = quickSort(arr);
console.log(sortedArr); // [1, 2, 3, 4, 5]
快速排序的思路是选取一个基准值,将数组中小于基准值的元素放到左边,大于基准值的元素放到右边,再递归地对左右两个子数组进行排序。