冒泡排序的写法:
//从小到大排列
var arr = [1,3,2,32,12,33,12,335,123]
for(var i = 0; i < arr.length;i++){
for(var j = 0; j < arr.length - i;j++){
if( arr[j] > arr[j+1]){
var temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
}
}
}
console.log(arr)
封装一个冒泡排序:
//从小到大排列
function getLking(arr){
for(var i = 0; i < arr.length;i++){
for(var j = 0; j < arr.length - i;j++){
if( arr[j] > arr[j+1]){
var temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
}
}
}
console.log(arr)
return arr
}
//调用
var maoPa = [1,3,44,22,11,23,123,21,456]
getLking(maoPa)
网友评论