使用很长时间c++,希望总结一下,为下一步更深入的学习和开发做准备。
就从今晚开始吧,嗯,从算法开始......
1、冒泡法排序
for(int i=0;i<n;i++)
{
for(int j=0;j=n-i-1;j++)
{
if(a[j]>a[j+1])
{
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
复杂度:n(n-1)/2
2、二分法查找
int high,low,mid;
mid=(int)(high+low)/2;
while(k!=a[mid])
{
if(k>a[mid])
low=mid+1;
if(k<a[mid])
high=mid-1;
mid=int(high+low)/2;
}
return mid;
只是适用于按大小排序的数列
穷举法
比如 组合
5中取3 的情况:
int a,b,c,count=1; for(a=1;a<=5;a++) for(b=1;b<=5;b++) for(c=1;a!=b&&c<=5;c++) if(c!=a&&c!=b) cout<<count++<<":"<<a<<","<<b<<","<<c<<" ";
int a,b,c,count=1; for(a=1;a<=5;a++) for(b=1;b<=5;b++) for(c=1;a!=b&&c<=5;c++) if(c!=a&&c!=b) cout<<count++<<":"<<a<<","<<b<<","<<c<<" ";
递归算法
比如阶乘函数
int ln(int n)
{
if(n==0||n==1)
return 1;
else return n*ln(n-1);
}
使用递归算法画杨辉三角的程序:
#include <iostream>
using namespace std;
int main()
{
int c(int x,int y);
int i,j,n=13;
while(n>12)
cin>>n;
for(i=0;i<=n;i++)
{
for(j=0;j<=(24-2*i)/2;j++)
cout<<" ";
for(j=1;j<i+2;j++)
cout<<c(i,j)<<" ";
cout<<endl;
}
return 0;
}
int c(int x,int y)
{
int z;
if(y==1||y==x+1) return 1;
z=c(x-1,y-1)+c(x-1,y);
return z;
}
使用递归算法打印二进制数的程序:
#include <iostream>
using namespace std;
int main()
{
void printb(int x, int n);
int x;
cout<<"input the number:"<<endl;
cin>>x;
cout<<"number of decimal form:"<<x<<endl;
cout<<"It`s binary form:";
printb(x,sizeof(int)*8);
return 0;
}
void printb(int x, int n)
{
if(n>0)
{
if(n%8==0)
cout<<" ";
cout<<(char)('0'+((unsigned)(x&(1<<(n-1)))>>(n-1)));
printb(x,n-1);
}
}
(1)完结