总结:冒泡排序分为两个循环
// 外层代表趟数(外层循环条件):数组长度-1
// 内层代表次数(内层循环条件):数组长度-趟数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
// 总结:冒泡排序分为两个循环
// 外层代表趟数:数组长度-1
// 内层代表次数:数组长度-趟数
let shu = [25, 42, 32, 2, 16]
for (let i = 0; i < shu.length - 1; i++) {
//趟数:数组长度-1 let i = 0;i<5-1=4;i++,当前为第一次,循环条件是四,会循环四次
for (let j = 0; j < shu.length - i; j++) {
//次数:数组长度-趟数(5)-(1)=4 当前为第一次,交换四次
// 比较:第一个数与第二个数(shu[j])(shu[j+1])
// 例如:当数组索引为0时,与索引加1的比较:
// 第一个索引号<第二个索引号:
// 条件为:第一个索引值>第二个索引值,进行索引值的交换
if (shu[j] > shu[j + 1]) {
let huan
huan = shu[j]
shu[j] = shu[j + 1]
shu[j + 1] = huan
}
}
}
console.log(shu)
</script>
</body>
</html>