固定算法,固定思路
- 找到中间位置 midValue
- 遍历数组,小于 midValue 放在 left,否则放在 right
- 继续递归。最后 concat 拼接返回
细节:获取 midValue 的两种方式
- 使用 splice ,会修改原数组
- 使用 slice ,不会修改原数组——更加推荐
/**
* @description 快速排序
* @author lsr
*/
/**
* 快速排序 - splice
* @param arr
* @returns
*/
export function quickSort1(arr: number[]): number[] {
const length = arr.length
if (length === 0) return arr
const left = []
const right = []
const midIndex = Math.floor(arr.length / 2)
const midValue = arr.splice(midIndex, 1)[0]
for (let i = 0; i < arr.length; i++) {
if (arr[i] < midValue) {
left.push(arr[i])
} else {
right.push(arr[i])
}
}
return quickSort1(left).concat([midValue], quickSort1(right))
}
/**
* 快速排序 - slice
* @param arr
* @returns
*/
export function quickSort2(arr: number[]): number[] {
const length = arr.length
if (length === 0) return arr
const left: number[] = []
const right: number[] = []
const midIndex = Math.floor(arr.length / 2)
const midValue = arr.slice(midIndex, midIndex + 1)[0]
for (let i = 0; i < arr.length; i++) {
if (i === midIndex) continue
if (arr[i] < midValue) {
left.push(arr[i])
} else {
right.push(arr[i])
}
}
return quickSort2(left).concat([midValue], quickSort2(right))
}
// 功能测试
// const arr = [1, 6, 2, 7, 3, 8, 4, 9, 5]
// const res = quickSort2(arr)
// console.log(res)
// 性能测试
// const arr1 = []
// for (let i = 0; i < 10 * 10000; i++) {
// arr1.push(Math.floor(Math.random() * 1000))
// }
// console.time('quickSort1')
// quickSort1(arr1)
// console.timeEnd('quickSort1') // 54.548095703125 ms
// const arr2 = []
// for (let i = 0; i < 10 * 10000; i++) {
// arr2.push(Math.floor(Math.random() * 1000))
// }
// console.time('quickSort2')
// quickSort2(arr2)
// console.timeEnd('quickSort2') // 52.547119140625 ms
// 单独比较 splice 和 slice
// const arr1 = []
// for (let i = 0; i < 10 * 10000; i++) {
// arr1.push(Math.floor(Math.random() * 1000))
// }
// console.time('splice')
// arr1.splice(5 * 10000, 1)
// console.timeEnd('splice') // 0.01123046875 ms
// const arr2 = []
// for (let i = 0; i < 10 * 10000; i++) {
// arr2.push(Math.floor(Math.random() * 1000))
// }
// console.time('slice')
// arr2.slice(5 * 10000, 5 * 10000 + 1)
// console.timeEnd('slice') // 0.001953125 ms
单元测试
/**
* @description 快速排序 test
* @author lsr
*/
import { quickSort1, quickSort2 } from '@/01-algorithm/guick-sort'
describe('快速排序', () => {
it('正常情况', () => {
const arr = [1, 6, 2, 7, 3, 8, 4, 9, 5]
const res = quickSort2(arr)
expect(res).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9])
})
it('空数组', () => {
const res = quickSort2([])
expect(res).toEqual([])
})
it('有负数', () => {
const arr = [1, 6, 2, -1, 3, -2, 4, -3, 5]
const res = quickSort2(arr)
expect(res).toEqual([-3, -2, -1, 1, 2, 3, 4, 5, 6])
})
it('全都一样', () => {
const arr = [1, 1, 1, 1, 1]
const res = quickSort2(arr)
expect(res).toEqual([1, 1, 1, 1, 1])
})
})
时间复杂度
- 有遍历,有二分——O(n*logn)或者O(nlogn)
- 常规排序,嵌套循环,复杂度是O(n^2)
splice 和 slice 没有区分出来
- 算法本身的时间复杂度就够高O(n*logn)
- 外加,splice是逐步二分之后执行的,二分会快速削减数量级
- 如果单独比较 splice 和 slice ,效果会非常明显