<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//冒泡排序
var arr = new Array(13,2,58,74,61);
console.log("排序前的数组:" + arr);
for(let i = 0; i < arr.length; i++){
for(let j = 0; j < arr.length - 1; j++){
if(arr[j] > arr[j+1]){
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
console.log(`排序后的数组:${arr}`);
//优化方法
var arr = [87,96,2,32,14,58,15];
console.log("排序前的数组:" + arr);
for(let i = 0; i < arr.length; i++){//外循环控制排序趟数
for(let j = i + 1; j < arr.length; j++){//内循环完成每趟排序
if(arr[i] > arr[j]){
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
console.log(`排序后的数组:${arr}`);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 计算斐波拉契数列的前20项之和
// 1 1 2 3 5 8 13 21 34......
var arr = new Array();
arr[0] = 1;
arr[1] = 1;
var temp = 0;
var sum = 0;
for(i = 2; i <= 20 ; i++){
arr[i] = arr[i - 1] + arr[i - 2];
temp += arr[i];
}
sum += arr[0] + arr[1] + temp;
console.log(sum);//17710
</script>
</body>
</html>
冒泡排序,斐波那契数列
最新推荐文章于 2024-09-09 09:35:48 发布