1. 程式人生 > 其它 >排序和搜尋

排序和搜尋

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 } } }