查找——实现监视哨法查找
#include<stdio.h>
#include<stdlib.h>
int cmp(const void *a,const void *b)
{
return *(int *)a-*(int *)b;
}
int main()
{
int a[101],i;
for(i=1;i<=100;i++)
a[i]=rand()%100;
for(i=1;i<=100;i++)
printf("%d ",a[i]);
printf("\n");
int key;
scanf("%d",&key);
printf("顺序查找\n");
a[0]=key;
for(i=100;i>=0;i--)
if(a[i]==key){
printf("%d\n",i);
break;
}
qsort(&a[1],100,sizeof(int),cmp);
for(i=1;i<=100;i++)
printf("%d ",a[i]);
printf("\n");
printf("折半查找\n");
int mid,start=1,end=100;
mid=(start+end)/2;
while(start<=end)
{
if(a[mid]==key){
printf("%d\n",mid);
break;
}
if(a[mid]>key){
end=mid-1;
mid=(end+start)/2;
}
else{
start=mid+1;
mid=(start+end)/2;
}
}
printf("end\n");
}
#include<stdio.h>
#include<stdlib.h>
int cmp(const void *a,const void *b)
{
return *(int *)a-*(int *)b;
}
int main()
{
int a[101],i;
for(i=1;i<=100;i++)
a[i]=rand()%100;
for(i=1;i<=100;i++)
printf("%d ",a[i]);
printf("\n");
int key;
scanf("%d",&key);
printf("顺序查找\n");
a[0]=key;
for(i=100;i>=0;i--)
if(a[i]==key){
printf("%d\n",i);
break;
}
qsort(&a[1],100,sizeof(int),cmp);
for(i=1;i<=100;i++)
printf("%d ",a[i]);
printf("\n");
printf("折半查找\n");
int mid,start=1,end=100;
mid=(start+end)/2;
while(start<=end)
{
if(a[mid]==key){
printf("%d\n",mid);
break;
}
if(a[mid]>key){
end=mid-1;
mid=(end+start)/2;
}
else{
start=mid+1;
mid=(start+end)/2;
}
}
printf("end\n");
}
博主ma6174对本博客文章(除转载的)享有版权,未经许可不得用于商业用途。转载请注明出处http://www.cnblogs.com/ma6174/
对文章有啥看法或建议,可以评论或发电子邮件到ma6174@163.com
本文转自ma6174博客园博客,原文链接:http://www.cnblogs.com/ma6174/archive/2012/01/05/2313327.html,如需转载请自行联系原作者