用JS 实现块组排序,并说明时间复杂度
题目:用 JavaScript 实现快速排序,并说明时间复杂度
思路:
快速排序是基础算法之一,算法思路是固定的
- 找到中间位置 midValue
- 遍历数组,小于 midValue 放在 left, 大于midValue 放在right
- 继续递归。最后 concat 拼接,返回
代码实现:
/** * @description 快速排序 */ export function quickSort(arr: number[]): number[]{ const length = arr.length if(length <=1 ) return arr const midIndex = Math.floor(length / 2) const midValue = arr[midIndex] const left: number[] = [] const right: number[] = [] for(let i = 0; i < length; i++){ if(i !== midIndex){ const temp = arr[i] if(temp < midValue){ //小于 midValue,放在 left left.push(temp) }else {//大于 midValue,放在 right right.push(temp) } } } return quickSort(left).concat([midValue],quickSort(right)) }
测试用例:
/** * @description 快速排序 测试 */ import {quickSort} from './quick-sort' describe('快速排序 测试',()=>{ it('正常数据',()=>{ const arr = [1, 6, 2, 7, 3, 8, 4, 9, 5] const res = quickSort(arr) expect(res).toEqual([1,2,3,4,5,6,7,8,9]) }) it('有负数情况',()=>{ const arr = [1, -6, 2, 7, -3,0, 8, 4, 9, 5] const res = quickSort(arr) expect(res).toEqual([-6,-3,0, 1,2,4,5,7,8,9]) }) it('所有元素都一样的情况',()=>{ const arr = [5,5,5] const res = quickSort(arr) expect(res).toEqual([5,5,5]) }) it('空数组',()=>{ const res = quickSort([]) expect(res).toEqual([]) }) })
性能分析:
时间复杂度: O(nlogn) --- 有遍历,有二分