冒泡算法的三种JavaScript表示

     以前学习冒泡算法,总是弄不清楚n和n-1等一些变量的关系,原因是没有弄明白它的真正含义,今天写了一个冒泡算法的JS小程序,终于弄明白了。
     
var  R1 = new  Array();
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 ;
var  R2 = new  Array( 35 , 55 , 65 , 20 , 30 , 25 , 0 , 7 , 5 , 3 );
var  R3 = new  Array( 35 , 55 , 65 , 20 , 30 , 25 , 0 , 7 , 5 , 3 );

function  BubbleSort1()
{
    
var  n = R1.length - 1 ;
    
for ( var  i = 1 ;i < n;i ++ )
    {
        
var  flag = false ;
        
for ( var  j = n - 1 ;j >= i;j -- )
        {
            
var  temp;
            
if (R1[j + 1 ] < R1[j])
            {
                temp
= R1[j + 1 ];
                R1[j
+ 1 ] = R1[j];
                R1[j]
= temp;
            }
            flag
= true ;
        }
        
if ( ! flag)  return ;        
    }
}

function  BubbleSort2()
{
    
var  n = R2.length;
    
for ( var  i = 0 ;i < n - 1 ;i ++ )
    {
        
var  flag = false ;
        
for ( var  j = n - 2 ;j >= i;j -- )
        {
            
var  temp;
            
if (R2[j + 1 ] < R2[j])
            {
                temp
= R2[j + 1 ];
                R2[j
+ 1 ] = R2[j];
                R2[j]
= temp;
            }
            flag
= true ;
        }
        
if ( ! flag)  return ;        
    }
}
function  BubbleSort3()
{
    
var  n = R3.length;
    
for ( var  i = 0 ;i < n - 1 ;i ++ )
    {
        
var  flag = false ;
        
for ( var  j = n - 1 ;j > i;j -- )
        {
            
var  temp;
            
if (R3[j] < R3[j - 1 ])
            {
                temp
= R3[j];
                R3[j]
= R3[j - 1 ];
                R3[j
- 1 ] = temp;
            }
            flag
= true ;
        }
        
if ( ! flag)  return ;        
    }
}
    调用它们的HTML文件代码如下:
   
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd" >
< html >
    
< head >
        
< meta  http-equiv ="Content-Type"  content ="text/html; charset=iso-8859-1"   />
        
< title > BubbleSort </ title >
        
< script  language ="javascript"  src ="bubblesort.js" ></ script >  
        
< script  language ="javascript" >
           BubbleSort1();
           BubbleSort2();
           BubbleSort3();
           
for ( var  z = 1 ;z < 11 ;z ++ )
           {
                document.write(R1[z]);
             
           }
           document.write(
" <br/> " );
           
for ( var  k = 0 ;k < 10 ;k ++ )
           {
                document.write(R2[k]);
                  
           }
           document.write(
" <br/> " );
           
for ( var  k = 0 ;k < 10 ;k ++ )
           {
                document.write(R3[k]);
        
           }
        
</ script >
    
</ head >
    
< body >
    
</ body >
</ html >

你可能感兴趣的:(JavaScript)