华为面试题汇总 下载本文

{

int low,high,mid; low=0;high=n-1; while(low<=high) {

mid=(low+high)/2;

if(a[mid].key==key) return mid; else if(a[mid].key

return -1; }

3. 递归计算如下递归函数的值(斐波拉契): f(1)=1 f(2)=1

f(n)=f(n-1)+f(n-2) n>2 解:非递归算法: int f(int n) {

int i,s,s1,s2;

s1=1;/*s1用于保存f(n-1)的值*/ s2=1;/*s2用于保存f(n-2)的值*/ s=1;

for(i=3;i<=n;i++) {

s=s1+s2; s2=s1; s1=s; }

return(s); }

递归算法: Int f(int n) {

If(n==1||n==2) Rerurn 1; Else

Rerutn f(n-1)+f(n-2); }

4. 交换两个数,不用第三块儿内存: 答:int a = ……; int b = ……; a = a + b; b = a - b;

a = a - b;

5. 冒泡排序:

答:void BubbleSort(elemtype x[],int n) //时间复杂度为0(n*n); { int i,j;

elemtype temp; for(i=1;i

if(x[j].key>x[j+1].key) {

temp=x[j]; x[j]=x[j+1]; x[j+1]=temp; } } }

//补充一个改进的冒泡算法:

void BubbleSort(elemtype x[],int n) {

Int i,j;

BOOL exchange; //记录交换标志 for(i=1;i

Exchange = false; For(j=n-1;j>=i;--j) {

If(x[j]>x[j+1]) {

x[0] = x[j]; X[j] = x[j+1]; X[j+1] = x[0];

Exchange = true; //发生了交换,设置标志为真. } }

if (!Exchange ) //为发生替换,提前终止算法 return; } }

6. c语言 文件读写 #include \main()

{

FILE *fp;

char ch,filename[10]; scanf(\

if((fp=fopen(filename,\{

printf(\exit(0); }

ch=getchar(); while(ch!='#') {

fputc(ch,fp); putchar(ch); ch=getchar(); }

fclose(fp); }

7. winsocket编程 //这个不错 // 服务器代码

#include #include void main() {

WORD wVersionRequested; //版本号 WSADATA wsaData; //数据 int err;

wVersionRequested = MAKEWORD(1,1);

err = WSAStartup(wVersionRequested,&wsaData); if( err != 0) {

return; }

if(LOBYTE( wsaData.wVersion ) != 1|| HIBYTE( wsaData.wVersion) != 1) {

WSACleanup(); return; }

SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0); //建立套接字 SOCKADDR_IN addrSrv;

addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);

addrSrv.sin_family=AF_INET; addrSrv.sin_port=htons(6000);

bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR)); //绑定端口 listen(sockSrv,5); //转换socket套接子为侦听套接子 SOCKADDR_IN addrClient; int len=sizeof(SOCKADDR); while(1) //无限循环 {

SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len); char sendBuf[100];

sprint(sendBuf,\inet_ntoa(addrClient.sin_addr));

send(sockConn,sendBuf,strlen(sendBuf)+1,0); char recvBuf[100];

recv(sockConn,recvBuf); printf(\closesocket(sockConn); WSACleanup(); } } 注:这是Server端;File->New->Win32 Console Application,工程名:TcpSrv;然后,File-> 第11/28页 ->New->C++

Source File,文件名:TcpSrv;在该工程的Setting的Link的Object/library modules项要加入ws2_32.lib

#include #include void main() {

WORD wVersionRequested; WSADATA wsaData; int err;

wVersionRequested = MAKEWORD(1,1);

err = WSAStartup(wVersionRequested,&wsaData); //启动winsock Dll if( err != 0) {

return; }

if(LOBYTE( wsaData.wVersion ) != 1|| HIBYTE( wsaData.wVersion) != 1) {

WSACleanup(); return; }