1 //冒泡排序实现 2 function bubleSort(myArray) 3 { 4 var temp=0; 5 for (var i = 0; i < myArray.length; i++) { 6 for (var j = 0; j < myArray.length-i; j++) { 7 if(myArray[j]>myArray[j+1]) 8 { 9 temp=myArray[j+1]; 10 myArray[j+1]=myArray[j]; 11 myArray[j]=temp; 12 } 13 }; 14 }; 15 16 return myArray; 17 } 18 //测试排序 19 function testBubleSort() 20 { 21 var myArray=initArray(); 22 var myArrayAfterSort=bubleSort(myArray); 23 for (var i = 0; i < myArrayAfterSort.length; i++) { 24 console.log(myArrayAfterSort[i]); 25 }; 26 } 27 //初始化数组 28 function initArray() 29 { 30 var myArray=[3,6,2,9,1]; 31 return myArray; 32 } 33 34 testBubleSort();