冒泡排序比较所有相邻的元素,如果第一个比第二个大,则交换一轮,可以保证最后一个数最大,执行n-1轮,并排序即可完成时间复杂度O(n^2)Array.prototype.bubbleSort=function(){constlen=this.lengthfor(leti=0;ithis[j+1]){consttemp=this[j]this[j]=this[j+1]this[j+1]=temp}}}//同上//for(leti=0;i=0;j--){//从后向前遍历//if(this[j]>this[j+1]){//consttemp=this[j]//this[j]=this[j+1]//this[j+1]=temp//}//}//}}constarr=[6,3,8,2,1]console.log('排序前',arr)arr.bubbleSort()console.log('排序后',arr)选择sort,找到数组中的最小值,选择它,放在第一个place然后找到第二小的值,选择它放在第二位进行n-1轮时间复杂度O(n^2)Array.prototype.selectionSort=function(){letlen=this.lengthletminIndex,tempfor(leti=0;i=0&&this[preIndex]>current){this[preIndex+1]=this[preIndex]preIndex--}this[preIndex+1]=current}}constarr=[7,0,6,3,4,2,5,1]console.log('排序前',arr)arr.插入onSort()console.log('aftersorting',arr)归并排序点:将数组拆分为两半,然后递归对子数组进行“拆分”操作,直到分成单独的数。合并成有序数组,然后合并有序数组,直到所有数组合并成一个完整的数组时间复杂度O(n*logN)Array.prototype.mergeSort=function(){//points(recursive)constrec=(arr)=>{if(arr.length===1)returnarrconstmid=Math.floor(arr.length/2)constleft=arr.slice(0,mid)constright=arr.slice(mid,arr.length)constorderLeft=rec(left)constorderRight=rec(right)returnmerge(orderLeft,orderRight)}//combinedconstmerge=(orderLeft,orderRight)=>{constres=[]while(orderLeft.length&&orderRight.length){如果(orderLeft[0]this[i]=n)}constarr=[7,0,6,3,4,2,5,1]console.log('排序前',arr)arr.mergeSort()console.log('排序后',arr)快速排序分区:从数组中任意选择一个“基准”,所有比较到benchmark较小的元素放在pivot之前,大于pivot的元素放在pivot之后Recursive:递归划分pivot前后的子数组。时间复杂度O(n*logN)Array.prototype.quickSort=function(){constrec=(arr)=>{if(arr.length<2)returnarrconstleft=[]constright=[]constmid=arr[0]for(leti=1;ithis[i]=n)}constarr=[7,0,6,3,4,5,2,1]console.log('排序前',arr)arr.quickSort()console.log('排序后',arr)