Bubble sort JS implementation

The basic idea

Compare the data from front to back, and if you find a value smaller than your own, the two values swap places, allowing the larger element to move back and forth, like a bubble rising.

Dynamic graph demonstration

Code implementation

    <script>
        function bubbleSort(n) {
            for (let i = 0; i < n.length- 1; i++) {
                for(let j=0; j<n.length- 1-i; j++){let tem;
                    if(n[j]>n[j+1]){
                        tem=n[j+1];
                        n[j+1]=n[j]; n[j]=tem; }}}return n;
        }
        let num = [9.7.5.8.6.4.2.6.1];
        console.log(bubbleSort(num));
    </script>
Copy the code