排序
https://visualgo.net/zh
排序:把某个乱序的数组变成升序或者降序的数组
js:sort
冒泡排序
*比较所有相邻元素,如果第一个比第二个大 ,则交换它们
*一轮下来。就可以保证最后一个数是最大的
*执行n-1轮,就可以完成排序
时间复杂度
*两个嵌套循环
*时间复杂度O(n^2)
Array.prototype.bubbleSort=function (){ for(let i=0;i<this.length-1;i++){ for(let j=0;j<this.length-1-i;j++){ if(this[j]>this[j+1]){ const temp=this[j] this[j]=this[j+1] this[j+1]=temp } } } }
选择排序
*找到数组中的最小值,选中它并将它放置在第一位
*接着找到第二小的值,选中它,并将其放在第二位
*依次类推,执行n-1轮
时间复杂度
*两个嵌套循环
*时间复杂度O(n^2)
Array.prototype.selectionSort=function (){ for(let i=0;i<this.length-1;i++){ let indexMin=i for(let j = i;this.length;j++){ if(this[j]<this[indexMin]){ indexMin=j } } if(indexMin!==i){ const temp=this[i] this[i]=this[indexMin] this[indexMin]=temp } } }
插入排序
*从第二个数开始往前比
*比它大救往后排
*依次类推进行到最后一个数
时间复杂度
*两个嵌套循环
*时间复杂度O(n^2)
Array.prototype.insertionSort=function (){ for(let i =1;i<this.length;i++){ const temp=this[i] let j = i ; while(j>0){ if(this[j-1]>temp){ this[j]=this[j-1] }else{ break } j-- } this[j]=temp } }
归并排序
*分:把数组劈成2半,再递归的对子数组进行“”分“操作”直到,分成一个个单独的数
*合:把2个数合并为有序数组,再对有序数组进行合并,直到全部子数组合并为一个完整数组
*新建一个空数组res,用于存放最终排序后的数组
*比较两个有序数组的头部,较小者出队并推入res中
*如果两个数组还有值,就重复第二步
时间复杂度
*分的时间复杂度是O(logN)
*合的时间复杂度是O(n)
*时间复杂度是O(n*logN)
Array.prototype.mergeSort=function (){ const rec=(arr)=>{ if(arr.length===1){return arr;} const mid =Math.floor(arr.length/2) const left =arr.slice(0,mid) const right=arr.slice(mid,arr.length) const orderLeft= rec(left) const orderRight=rec(right) const res = [] while (orderLeft.length || orderRight.length){ if(orderLeft.length&&orderRight.length){ res.push(orderLeft[0]<orderRight[0]?orderLeft.shift():orderRight.shift()) }else if(orderLeft.length){ res.push(orderLeft.shift()) }else if(orderRight.length){ res.push(orderRight.shift()) } } return res } const res = rec(this) res.forEach((n,i)=>{ this[i]=n }) }
快速排序
*分区:从数组中任意选一个“基准”,所有比基准小的元素放基准前面,比基准大的元素放在基准后面
*递归:递归地对基准前后的子数组进行分区
时间复杂度
*递归的时间复杂度是O(logN)
*分区的时间复杂度是O(n)
*时间复杂度是O(n*logN)
Array.prototype.quickSort=function (){ const rec=()=>{ if(arr.length===1){return arr;}//如果元素只有一个他必然有序 const left=[] const right=[] const mid=arr[0];//设置基准 for(let i =1;i<arr.length;i++){//重第二个元素开始,到结束 if(arr[i]<mid){//如果元素比基准小放左边的数组 left.push(arr[i]) }else{ right.push(arr[i]) } } return [...rec(left),mid,...rec(right)] } const res =rec(this) res.forEach((n,i)=>{ this[i]=n }) }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人