细节
function quickSort1 (arr:number[]):number[] {
const len = arr.length
if (len === 0) return arr
const midIdx = Math.floor(len / 2)
const midValue = arr.splice(midIdx,1)[0]
const left:number[] = []
const right:number[] = []
// 由于splice改变了原数组,所以不能使用len作为循环条件
for (let i = 0; i < arr.length; i++) {
if (arr[i] < midValue) {
// 小于中间值,放left
left.push(arr[i])
} else {
// 大于或者等于,放right
right.push(arr[i])
}
}
return quickSort1(left).concat([midValue],quickSort1(right))
}
function quickSort2 (arr:number[]):number[] {
const len = arr.length
if (len === 0) return arr
const midIdx = Math.floor(len / 2)
const midValue = arr.slice(midIdx,midIdx + 1)[0]
const left:number[] = []
const right:number[] = []
for (let i = 0; i < len; i++) {
if (i !== midIdx) {
if (arr[i] < midValue) {
// 小于中间值,放left
left.push(arr[i])
} else {
// 大于或者等于,放right
right.push(arr[i])
}
}
}
return quickSort2(left).concat([midValue],quickSort2(right))
}
const arr1 = [1,6,2,4,3,7,5,8,9]
quickSort1(arr1)
结果
[1, 2, 3, 4, 5, 6, 7, 8, 9]
const arr1 = [1,6,2,4,3,7,5,8,9]
quickSort2(arr1)
结果
[1, 2, 3, 4, 5, 6, 7, 8, 9]
describe('快速排序', () => {
it('正常情况', () => {
const arr = [1, 6, 2, 4, 3, 7, 5, 8, 9]
const res = quickSort1(arr)
expect(res).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9])
const arr2 = [1, 6, 2, 4, 3, 7, 5, 8, 9]
const res2 = quickSort2(arr2)
expect(res2).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9])
})
it('有负数', () => {
const arr = [-1, -6, 2, 4, 3, 7, 5, 8, 9]
const res = quickSort1(arr)
expect(res).toEqual([-6, -1, 2, 3, 4, 5, 7, 8, 9])
const arr2 = [-1, -6, 2, 4, 3, 7, 5, 8, 9]
const res2 = quickSort2(arr2)
expect(res2).toEqual([-6, -1, 2, 3, 4, 5, 7, 8, 9])
})
it('数值一样', () => {
const arr = [2, 2, 2, 2]
const res = quickSort1(arr)
expect(res).toEqual([2, 2, 2, 2])
const arr2 = [2, 2, 2, 2]
const res2 = quickSort2(arr2)
expect(res2).toEqual([2, 2, 2, 2])
})
it('空数组', () => {
const res = quickSort1([])
expect(res).toEqual([])
const res2 = quickSort2([])
expect(res2).toEqual([])
})
})
const test1 = []
for (let i = 0; i < 100 * 10000; i++) {
const n = Math.floor(Math.random() * 10000)
test1.push(n)
}
console.time('quickSort1')
quickSort1(test1)
console.timeEnd('quickSort1')
const test2 = []
for (let i = 0; i < 100 * 10000; i++) {
const n = Math.floor(Math.random() * 10000)
test2.push(n)
}
console.time('quickSort2')
quickSort2(test2)
console.timeEnd('quickSort2')
打印结果
quickSort1: 713.186ms
quickSort2: 685.652ms
splice 和 slice 没有区分出来
const test1 = []
for (let i = 0; i < 100 * 10000; i++) {
const n = Math.floor(Math.random() * 10000)
test1.push(n)
}
console.time('splice')
test1.splice(50 * 10000 , 1)
console.timeEnd('splice')
const test2 = []
for (let i = 0; i < 100 * 10000; i++) {
const n = Math.floor(Math.random() * 10000)
test2.push(n)
}
console.time('slice')
test1.slice(50 * 10000 ,50 * 10000 + 1)
console.timeEnd('slice')
打印结果
splice: 0.657ms
slice: 0.021ms
slice 本身优于splice