js bubble sort algorithm

<script>

        // 首先准备一个要排序的数组
        let arr = [21,34,2,4,55,98,3];

        // 创建一个函数,参数为我们要排序的数组
        function maopao(arr){
            // 声明一个变量作为临时存储数据的地方,用来等会坐变量的对调
            let temp;

                    // 数组的长度减一,是因为不需要遍历最后一个数
            for(let i = 0; i < arr.length-1; i++){
// j要减 1 在减 i ,也就是说 i 循环 需要循环 0-4次,j 循环分别循环 0-4次,0-3次,0-2次和0-1次
// 每次循环下来都要缩短目标,不需要对比最后一个数,这就是减去 i 的作用
                for(let j = 0; j<arr.length-1-i; j++){
                    // 让相邻的两个元素进行比较
                    if(arr[j]>arr[j+1]){
                        // 在遍历的过程中做值的互换
                        temp = arr[j];
                        arr[j] = arr[j+1];
                        arr[j+1] = temp;
                    }
                }
            }
            return arr;
        }

        console.log(maopao(arr));
        //[2, 3, 4, 21, 34, 55, 98]
    </script>

There is a formula for the bubbling algorithm:

 A pile of data is sorted, and the pair is smaller than the first, the outer loop N (array length)-1, the inner loop N-1-i

Guess you like

Origin blog.csdn.net/lolhuxiaotian/article/details/122337007