用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) --- 有遍历,有二分

posted @   yangkangkang  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示