用js写一个快速排序算法
function quickSort(arr) { if (arr.length <= 1) { return arr; } const pivotIndex = Math.floor(arr.length / 2); const pivot = arr[pivotIndex]; const leftArr = []; const rightArr = []; for (let i = 0; i < arr.length; i++) { if (i === pivotIndex) { continue; } if (arr[i] < pivot) { leftArr.push(arr[i]); } else { rightArr.push(arr[i]); } } return [...quickSort(leftArr), pivot, ...quickSort(rightArr)]; }
//Example:
const arr = [5, 3, 7, 1, 9, 2]; console.log(quickSort(arr)); // [1, 2, 3, 5, 7, 9]
原文地址: https://www.cveoy.top/t/topic/gRP 著作权归作者所有。请勿转载和采集!