1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="gb2312"> 5 <title>冒泡排序法</title> 6 </head> 7 8 <body> 9 <script> 10 var a=3;var b=5; 11 a=a+b; 12 b=a-b; 13 a=a-b; 14 console.log(a); 15 console.log(b); 16 17 /*冒泡排序法*/ 18 19 var array=[5,4,3,2,1]; 20 console.log("原数组"); 21 console.log(array); 22 function swap(index1,index2){ 23 var aux=array[index1]; 24 array[index1]=array[index2]; 25 array[index2]=aux; 26 27 } 28 29 for(var i=0;i<array.length;i++){ 30 for(var j=0; j<array.length-1;j++){ 31 if(array[j]>array[j+1]){ 32 swap(j,j+1); 33 } 34 console.log(array); 35 } 36 37 } 38 39 /*改进后的排序*/ 40 var array=[5,4,3,2,1]; 41 console.log("原数组"); 42 console.log(array); 43 function swap(index1,index2){ 44 var aux=array[index1]; 45 array[index1]=array[index2]; 46 array[index2]=aux; 47 48 } 49 50 for(var i=0;i<array.length;i++){ 51 for(var j=0; j<array.length-1-i;j++){ 52 if(array[j]>array[j+1]){ 53 swap(j,j+1); 54 } 55 56 } 57 console.log(array); 58 } 59 60 </script> 61 </body> 62 </html>