In the past, when I learned bubble algorithms, I always couldn't figure out the relationship between some variables such as n and n-1. The reason was that I didn't understand its true meaning. Today I wrote a JS small program for bubble algorithms and finally figured it out.
The code copy is as follows:
varR1=newArray();
R1[1]=35;
R1[2]=55;
R1[3]=65;
R1[4]=20;
R1[5]=30;
R1[6]=25;
R1[7]=0;
R1[8]=7;
R1[9]=5;
R1[10]=3;
varR2=newArray(35,55,65,20,30,25,0,7,5,3);
varR3=newArray(35,55,65,20,30,25,0,7,5,3);
functionBubbleSort1()
{
varn=R1.length-1;
for(vari=1;i<n;i++)
{
varflag=false;
for(varj=n-1;j>=i;j--)
{
vartemp;
if(R1[j+1]<R1[j])
{
temp=R1[j+1];
R1[j+1]=R1[j];
R1[j]=temp;
}
flag=true;
}
if(!flag)return;
}
}
functionBubbleSort2()
{
varn=R2.length;
for(vari=0;i<n-1;i++)
{
varflag=false;
for(varj=n-2;j>=i;j--)
{
vartemp;
if(R2[j+1]<R2[j])
{
temp=R2[j+1];
R2[j+1]=R2[j];
R2[j]=temp;
}
flag=true;
}