function quickSort(arr) { var len = arr.length if (len <= 1) { return arr } let leftArr = [] let rightArr = [] let pivotIndex = Math.floor(arr.length / 2); var pivot = arr.splice(pivotIndex, 1)[0] for (let i = 0; i < len - 1; i++) { if (arr[i] < pivot) { leftArr.push(arr[i]) } else { rightArr.push(arr[i]) } } return quickSort(leftArr).concat([pivot], quickSort(rightArr)) } var arr = [1, 3, 5, 7, 8, 6, 4, 2] console.log(quickSort(arr)) //[1,2,3,4,5,6,7,8]
//es6实现快速排序
function quickSort(arr){ if(!arr.length){ return [] } const [pivot,...rest] = arr return [...quickSort(rest.filter(item=>item<pivot)),pivot,...quickSort(rest.filter(item=>item>=pivot))] } var arr = [7,9,5,2,4,3,1,8] console.log(quickSort(arr)) //[1,2,3,4,5,6,7,8] ES6,真香!