以前图广度,学的知识不过脑子。重学下快排。记录下学习历程!bash
一遍写下来虽然花了很多时间,但感受对为于一些模糊的问题都有了比较深入的认识,好比为何快排是不稳定的学习
告别不爱动手的坏毛病ui
const arr = [45, 10, 11, 88, 34, 90]
// const quickSort = arr => {
// if (arr.length < 2) return arr
// const spliceItem = arr.splice(0, 1)
// const leftPointArr = []
// const rightPointArr = []
// arr.forEach(item => {
// if (item >= spliceItem) rightPointArr.push(item)
// else leftPointArr.push(item)
// });
// return leftPointArr.concat(spliceItem, rightPointArr);
// }
const quickSort = (arr, left = 0, right = arr.length - 1) => {
const pivot = arr[Math.ceil((left + right)/ 2 )] //中间值为基准值
let leftPoint = left
let rightPoint = right
let index
if (left < right) {
while (leftPoint < rightPoint) {
while(arr[rightPoint] > pivot) {
rightPoint--
}
while(arr[leftPoint] < pivot) {
leftPoint++
}
[arr[leftPoint], arr[rightPoint]] = [arr[rightPoint], arr[leftPoint]]
}
index = leftPoint
quickSort(arr, left, index - 1)
quickSort(arr, index + 1, right)
}
return arr
}
console.log(quickSort(arr))
复制代码