冒泡排序

原理:冒泡排序比較任何兩個相鄰的項,如果第一個比第二個大,則交換它們。元素項向上移動至 正確的順序,就好像氣泡升至表面一樣,冒泡排序因此得名。

圖解:


JS實現:

'use strict';

function bubbleSort(array){
    for(let i=0;i<array.length;i++){
        // 每次外部循環結束後,最末位置array.length-i-1下標位置的數被確定.
        for(let j=0;j<array.length-i;j++){
            if(array[j]>array[j+1]){
                swap(j,j+1,array);
            }
        }
    }
    return array;
}

function swap(index1,index2,array){
    const tmp=array[index2];
    array[index2]=array[index1];
    array[index1]=tmp;
}

function test(){
    const array=[5,4,3,2,3,3,1,8,4,7,9,6];
    const res=bubbleSort(array);
    console.log(res);
}
test();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章