<script>
var arr = [8, 9, 2, 4, 1];
//第一趟比较
for (var i = 0; i < arr.length; i++) {
if (arr[i] >= arr[i + 1]) {
var temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
console.log(arr);
//第二趟比较
for (var i = 0; i < arr.length - 1; i++) {
if (arr[i] >= arr[i + 1]) {
var temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
console.log(arr);
//第三趟比较
for (var i = 0; i < arr.length - 2; i++) {
if (arr[i] >= arr[i + 1]) {
var temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
console.log(arr);
//第四趟比较
for (var i = 0; i < arr.length - 3; i++) {
if (arr[i] >= arr[i + 1]) {
var temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
console.log(arr);
//外层循环是趟数,内层做比较
for (var i = 1; 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);
</script>
03-07
8931
10-10
579
11-03
532
11-03
462
10-31
798