34. Bubble sort

Time:2021-3-11

Reference website https://visualgo.net/

Bubble sort:

Compare the two numbers in pairs

Before < after, the latter one continues to compare with the next one

Before > after, switch positions, and then compare with the next one

After the first round of comparison, the position of the last number can be determined

The second round is used to determine the position of the penultimate

Until sorting is complete

arr.length = 5

About J< arr.length -I-1, because we start from 0 in the first, then we look at round 0, J

J < 5-0-1 means J < 4, that is to say, the maximum value of J is 3, and arr [3] is compared with arr [3 + 1]

Number of rounds / I 0 1 2 3 4 Comparison times/ arr.length -i-1
0 5 4 3 2 1 4
1 4 3 2 1 5 3
2 3 2 1 4 5 2
3 2 1 3 4 5 1
  1 2 3 4 5  

Note that each round can be compared 4 times, only the algorithm takes up memory

let arr = [5,4,3,2,1]for(let i = 0; i <  arr.length ; I + +) {// rounds of comparison for (let J = 0; J< arr.length  -I - 1; j + +) {// if (arr [J] > arr [J + 1]) {let a = arr [J] arr [J] = arr [J + 1] arr [J + 1] = a}}