冒泡排序

原理:冒泡排序比较任何两个相邻的项,如果第一个比第二个大,则交换它们。元素项向上移动至 正确的顺序,就好像气泡升至表面一样,冒泡排序因此得名。

图解:


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();

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