冒泡排序

冒泡排序

  • 遍历n-1次
  • 比较次数递减

每一趟把最大值放到最右边

function BubbleSort(arr){
    let n = arr.length;
    //遍历趟数
    for (let i = 0; i < n - 1; i++){
        //比较次数
        for (let j = 0; j < n - 1 - i; j++){
            //升序
            if (arr[j] > arr[j + 1]){
                let temp = arr[j+1]
                arr[j+1] = arr[j]
                arr[j] = temp
            }
            // console.log(...arr);
        }
        console.log(...arr,`current is [${i}]`);
    }
}

BubbleSort([21,4,65,9,5,2,125,54,234,87,33])
4 21 9 5 2 65 54 125 87 33  234 'current is [0]'
4 9 5 2 21 54 65 87 33  125 234 'current is [1]'
4 5 2 9 21 54 65 33  87 125 234 'current is [2]'
4 2 5 9 21 54 33  65 87 125 234 'current is [3]'
2 4 5 9 21 33  54 65 87 125 234 'current is [4]'
2 4 5 9 21  33 54 65 87 125 234 'current is [5]'
2 4 5 9  21 33 54 65 87 125 234 'current is [6]'
2 4 5  9 21 33 54 65 87 125 234 'current is [7]'
2 4  5 9 21 33 54 65 87 125 234 'current is [8]'
2 4 5 9 21 33 54 65 87 125 234 'current is [9]'
Written on June 25, 2024