console.log("=".repeat(30));
console.log("打印费氏级数:");
function printFibonacci(n){
if(n==0){
return 0;
}else if(n==1){
return 1;
}else if(n>=2){
return n+printFibonacci(n-1);
}else{
return "传入的参数有误,请检查";
}
}
console.log(printFibonacci(0));
console.log(printFibonacci(1));
console.log(printFibonacci(2));
console.log(printFibonacci(3));
console.log(printFibonacci(4));
console.log(printFibonacci(5));
//----------------------------------------------------
console.log("=".repeat(30));
console.log("二分查找:");
//有序数组
function binarySearch(arr,item){
let arrLength=arr.length;
let start=0,end=arrLength;
while(start<end){
let tmpLength=parseInt((end+start)/2);
if(item<arr[tmpLength]){
end=tmpLength;
}else if(item>arr[tmpLength]){
start=tmpLength;
}else if(item==arr[tmpLength]){
return tmpLength;
}
}
return -1;
}
let ary1=[4,6,8,10,12,14,16];
console.log(binarySearch(ary1,4));
console.log(binarySearch(ary1,6));
console.log(binarySearch(ary1,8));
console.log(binarySearch(ary1,10));
console.log(binarySearch(ary1,12));
console.log(binarySearch(ary1,14));
console.log(binarySearch(ary1,16));
console.log(binarySearch(ary1,1));
//----------------------------------------------------
console.log("=".repeat(30));
console.log("冒泡排序:");
function bubbleSort(arr){
let arrLength=arr.length;
for (let i = 0; i < arrLength; i++) {
for (let j = 0; j < arrLength-i; j++) {
if(arr[j]>arr[j+1]){
let tmp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=tmp;
}
}
}
}
let bubbleAry1=[55,32,189,110,10,66];
let bubbleAry2=[90,57,32,223,88,66];
bubbleSort(bubbleAry1);
bubbleSort(bubbleAry2);
console.log("bubbleAry1="+bubbleAry1);
console.log("bubbleAry2="+bubbleAry2);
//----------------------------------------------------
console.log("=".repeat(30));
console.log("选择排序:");
function selectSort(arr){
let arrLength=arr.length;
for (let i = 0; i < arrLength; i++) {
let maxIndex=0;
for (let j = 0; j < arrLength-i; j++) {
if(arr[maxIndex]<arr[j]){
maxIndex=j;
}
}
let tmp=arr[maxIndex];
arr[maxIndex]=arr[arrLength-1-i];
arr[arrLength-1-i]=tmp;
}
}
let selectAry1=[6,3,9,12,17,5];
let selectAry2=[18,5,3,9,10,2,7];
selectSort(selectAry1);
selectSort(selectAry2);
console.log("selectAry1="+selectAry1);
console.log("selectAry2="+selectAry2);
费氏级数 二分查找 冒泡 排序 js版
最新推荐文章于 2022-04-13 10:34:29 发布
本文通过具体实例详细介绍了几种常见的算法实现,包括递归求解斐波那契数列、二分查找、冒泡排序及选择排序等,为读者提供了一个从理论到实践的学习路径。
3339

被折叠的 条评论
为什么被折叠?



