Sorting principle of js array sort

Everyone knows that javascript arrays have a sort sorting method, which can achieve ascending and descending order. Now let's learn the principle of sort method bubble sort.
Bubble sort: compare the current item of the array with the next item, if the current item is greater than the next item, the two exchange positions.

 let arr = [100, 34, 16, 3, 18, 70];

 for (var i = 1; i < ary.length; i++) {
    for (var j = 0; j < ary.length - i; j++) {
      if (ary[j] > ary[j + 1]) {
        [ary[j], ary[j + 1]] = [ary[j + 1], ary[j]]
      }
    }
  }

The first layer of loop determines the number of loop rounds, and the second layer of loop compares the current item with the next item. If the current item is greater than the latter item, the position is exchanged. The ES6 method is used above to achieve the position exchange.

//第一轮 i=1;
  //j=0    arr[j]>arr[j+1]  arr[0]>arr[1]   100>34   交换位置  [34,100,16,3,18,70];
  //j=1    arr[j]>arr[j+1]  arr[1]>arr[2]   100>16   交换位置  [34,16,100,3,18,70];
  //j=2    arr[j]>arr[j+1]  arr[2]>arr[3]   100>3    交换位置  [34,16,3,100,18,70];
  //j=3    arr[j]>arr[j+1]  arr[3]>arr[4]   100>18   交换位置  [34,16,3,18,100,70];
  //j=4    arr[j]>arr[j+1]  arr[4]>arr[5]   100>70   交换位置  [34,16,3,18,70,100,];
  //j<5  arr.length-i

  //第二轮 i=2;  [34,16,3,18,70,100,];
  //j=0    arr[j]>arr[j+1]  arr[0]>arr[1]   34>16    交换位置   [16,34,3,18,70,100,];
  //j=1    arr[j]>arr[j+1]  arr[1]>arr[2]   34>3     交换位置   [16,3,34,18,70,100,];
  //j=2    arr[j]>arr[j+1]  arr[2]>arr[3]   34>18    交换位置   [16,3,18,34,70,100,];
  //j=3    arr[j]>arr[j+1]  arr[3]>arr[4]   34<70    不交换位置 [16,3,18,34,70,100,];
  //j<4

  //第三轮 i=3;  [16,3,18,34,70,100,];
  //j=0    arr[j]>arr[j+1]  arr[0]>arr[1]   16>3     交换位置   [3,16,18,34,70,100,];
  //j=1    arr[j]>arr[j+1]  arr[1]>arr[2]   16<18    不交换位置 [3,16,18,34,70,100,];
  //j=2    arr[j]>arr[j+1]  arr[2]>arr[3]   18<34    不交换位置 [3,16,18,34,70,100,];

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325070139&siteId=291194637