JavaScript bubble sort
1. Bubble sort
-
Bubble sort (compare adjacent numbers in pairs)
-
Implementation code:
let arr = [22, 55, 5, 88, 66, 77, 111, 3]; for (var j = arr.length - 1; j > 0; Var I = 0; var I = 0; i < j; i++) { if (arr[i] > arr[i + 1]) { var temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; }}}Copy the code
2. Analyze the code implementation process
-
Simple analysis
- First round traversal: seven times
- Second round traversal: six times
- Third round: five times
- .
-
Steps:
-
We find that the code is repeated, but the difference is the number of times each round is traversed. First: rank the largest number at the end
for (var i = 0; i < arr.length - 1; I++) {/ / seven times the if (arr [I] > arr [I + 1]) {var temp = arr [I]; arr[i] = arr[i + 1]; arr[i + 1] = temp; }}Copy the code
-
Then: Continue to rank the largest number to the second-to-last (the last number is already the maximum, so don’t iterate over it).
for (var i = 0; i < arr.length - 2; I++) {/ / six times the if (arr [I] > arr [I + 1]) {var temp = arr [I]; arr[i] = arr[i + 1]; arr[i + 1] = temp; }}Copy the code
-
Continue: Continue to rank the largest number to the third from the bottom (the last two are not iterated again)
for (var i = 0; i < arr.length - 3; Five i++) {/ / the if (arr [I] > arr [I + 1]) {var temp = arr [I]; arr[i] = arr[i + 1]; arr[i + 1] = temp; }}Copy the code
-
And so on…………..
\
-