Bubble sort: The elements in an array are arranged in order from large to small or from small to large.
var array=[9,8,7,6,5,4,3,2,1];
First round comparison: 8,7,6,5,4,3,2,1,9 exchanged 8 times i=0 j=array.length-1-i
Second round comparison: 7,6,5,4,3,2,1,8,9 exchanged 7 times I=1 J=array.length-1-i
Third round comparison: 6,5,4,3,2,1,7,8,9 exchanged 6 times i=2 J=array.length-1-i
Fourth round comparison: 5,4,3,2,1,6,7,8,9 exchanged 5 times i=3 J=array.length-1-i
Fifth round comparison: 4,3,2,1,5,6,7,8,9 exchanged 4 times i=4 j=array.length-1-i
Sixth round comparison: 3,2,1,4,5,6,7,8,9 exchanged 3 times i=5 j=array.length-1-i
Seventh round comparison: 2,1,3,4,5,6,7,8,9 exchanged 2 times i=6 j=array.length-1-i
Eighth round comparison: 1,2,3,4,5,6,7,8,9 exchanged 1 times i=7 j=array.length-1-i
Code implementation:
var temp;
var array=[9,8,7,6,5,4,3,2,1];
External loop control Wheel number
For (Var i=0;i<array.length-1;i++) {
Internal loop control comparison times
For (Var j=0;j<array.length-1-i;j++) {
if (array[j]>array[j+1]) {
Swap two variables
Temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
Console.log (array);
Code optimization:
var temp,bool,m=0;
var array=[9,8,7,6,5,4,3,2,1];
For (Var i=0;i<array.length-1;i++) {
//switch in the open/closed principle
bool = true;
For (Var j=0;j<array.length-1-i;j++) {
if (array[j]>array[j+1]) {
//exchange of two variables
Temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
bool=false;//Turn off the switch
}
}
if the inner loop is not executed (switch off, execute the following statement);
if (bool) {
Break ;
}
m++;
}
Console.log (array+ ", compare" +m+ "wheel");
Note: Compare the number of wheels best for 0 rounds, the worst is 8 rounds
Bubble sort in JavaScript