algorithm

In round I, the two adjacent values are compared from back to front. If A [J-1]> A [j], the two positions are switched until the i-th round is n-1

Time complexity


( n 1 ) + ( n 1 ) + . . . + 1 = O ( n 2 ) (n-1)+(n-1)+… +1= O(n^2)

js

const input = [4.2.15.2.5.6.21.67.2.3]
const sort = (arr) = > {
    for (let i = 0; i < arr.length; i++) {
        for (let j = arr.length-1; j>i; j--) {
            const a = arr[j]
            const b = arr[j-1]
            if (a<b) {
                arr[j-1] = a
                arr[j] = b
            }
        }
    }
    return arr;
}
console.log(sort(input))
Copy the code