当前位置:网站首页>Bubble sort

Bubble sort

2022-07-06 04:36:00 A distant youth

Bubble sort is a simple sort algorithm . It repeatedly visits the sequence to be sorted , Compare two elements at a time , If they are in the wrong order, exchange them . The job of the interview sequence is to repeat until there is no need to exchange , That is to say, the sequence has been sorted . The name of this algorithm comes from the fact that the smaller the elements, the more slowly “ floating ” Go to the top of the list .

1.1 Algorithm description

  • Compare adjacent elements . If the first one is bigger than the second one , Just exchange the two of them ;
  • Do the same for each pair of adjacent elements , From the beginning of the first couple to the end of the last couple , So the last element should be the largest number ;
  • Repeat the above steps for all elements , Except for the last one ;
  • Repeat step 1~3, Until sorting is complete .

1.2 Dynamic diagram demonstration

 

1.3 Code implementation


function bubbleSort(arr) {
    var len = arr.length;
    for (var i = 0; i < len - 1; i++) {
        for (var j = 0; j < len - 1 - i; j++) {
            if (arr[j] > arr[j+1]) {        //  Comparison of two adjacent elements 
                var temp = arr[j+1];        //  Element exchange 
                arr[j+1] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}

原网站

版权声明
本文为[A distant youth]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132207155925.html