<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>冒泡排序</title>
</head>
<body>
<script>
var arr = [1, 5, 3, 95, 64, 78, 22, 24, 18, 53, 4, 90];
arr.sort();
console.log("sort:",arr);
arr.sort(function(a, b){
return a - b;
})
console.log("sort1:",arr);
arr.sort(function(a, b){
return b - a;
})
console.log("sort2:",arr);
function zdSrot(arr) {
for(let i = 0; i < arr.length - 1; i++){ //减1是因为排到最后的时候就是最大的了,可以不用再重复一次
for(let j = 0; j < arr.length - 1 - i; j++){ //减1减i可以减少重复的排序动作
if(arr[j] > arr[j+1]){
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
console.log(zdSrot(arr));
</script>
</body>
</html>