C语言经典算法

//(按升序排列)二分查找 #include\

intBinSearch(int r[],intn,int k){ int low=0,high=n-1,mid,count=0; while(low<=high) { mid=(low+high)/2; printf(\第%d次查找,在[%d,%d]中查找到r[%d]:%d\\n\ if(k==r[mid]) return mid; else if(k>r[mid])//如果待查找数列按降序排列此处要改成“<” low=mid+1; else high=mid-1; } return -1; }

void main(){ int n,m,x[20]={0,1,3,4,6,8,9,12,13,15,17,18,19,22,24,28,29,30,32,35}; printf(\请输入要查找的数:\\n\ scanf(\ m=BinSearch(x,20,n); if(m==-1)

printf(\在数列中没有找到此数\ else printf(\在数列中位置的下标是:%d\\n\}

元素

//n年几头母牛 #include%unsigned cow1(int n){ inti,a[5]; unsigned sum=0; for(i=1;i<=n;i++) {

if(i==1){a[1]=1;a[2]=a[3]=a[4]=0;} else if(i==2){a[1]=0;a[2]=1;a[3]=a[4]=0;} else if(i==3){a[1]=a[2]=0;a[3]=1;a[4]=0;} else{a[4]=a[3]+a[4];a[3]=a[2];a[2]=a[1];a[1]=a[4];} } for(i=1;i<=4;i++) sum+=a[i]; return sum; }

unsigned cow2(int n){ if(n<=3) return 1; else return (cow2(n-1)+cow2(n-3)); }

void main (){ int n; unsigned sum1,sum2; printf(\请输入年份:\\n\ scanf(\ sum1=cow1(n); printf(\第%d年共有%u头母牛\\n\ sum2=cow2(n); printf(\第%d年共有%u头母牛\\n\}

//按字母出现次序依次输出出现过的字母 #include\#include\void main(){ char x[80],y[26]; unsignedi; intj,n=0; puts(\ gets(x);

for(i=0;i='A'&&x[i]<='Z') {

for(j=0;j

printf(\依次出现的大写字母是:\\n\ for(j=0;j

printf(\ } }

联系客服:779662525#qq.com(#替换为@) 苏ICP备20003344号-4