排序和搜索
作者:互联网
https://visualgo.net/zh
冒泡排序
*比较所有相邻元素,如果第一个比第二个大 ,则交换它们
*一轮下来。就可以保证最后一个数是最大的
*执行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!==!){ const temp=this[i] this[i]=this[indexMin] this[indexMin]=temp } } }
标签:function,prototype,复杂度,嵌套循环,let,搜索,排序 来源: https://www.cnblogs.com/xwj-web/p/16250742.html