哎,我就辛苦辛苦了啦。
以下是可以编译运行的代码,在VC6.0下通过。
#include <stdio.h>
#define LENGTH 20
void SequenceSearch(int *fp,int Length);
void Search(int *fp,int length);
void Sort(int *fp,int length);
void main()
{
int count;
int arr[LENGTH];
printf("请输入你的数据的个数:\n");
scanf("%d",&count);
printf("请输入%d个数据\n",count);
for(int i=0;i<count;i++)
{
scanf("%d",&arr[i]);
}
int choise=0;
do
{
printf("1.使用顺序查询.\n2.使用二分查找法查找.\n3.退出\n");
scanf("%d",&choise);
if(choise==1)
SequenceSearch(arr,count);
else if(choise==2)
Search(arr,count);
else if(choise==3)
break;
} while (choise==1||choise==2||choise==3);
}
void SequenceSearch(int *fp,int Length)
{
int data;
printf("开始使用顺序查询.\n请输入你想要查找的数据.\n");
scanf("%d",&data);
for(int i=0;i<Length;i++)
if(fp[i]==data)
{
printf("经过%d次查找,查找到数据%d.\n",i+1,data);
return ;
}
printf("经过%d次查找,未能查找到数据%d.\n",i,data);
}
void Search(int *fp,int length)
{
int data;
printf("开始使用顺序查询.\n请输入你想要查找的数据.\n");
scanf("%d",&data);
printf("由于二分查找法要求数据是有序的,现在开始为数组排序.\n");
Sort(fp,length);
printf("数组现在已经是从小到大排列,下面将开始查找.\n");
int bottom,top,middle;
bottom=0;
top=length;
int i=0;
while (bottom<=top)
{
middle=(bottom+top)/2;
i++;
if(fp[middle]<data)
{
bottom=middle+1;
}
else if(fp[middle]>data)
{
top=middle-1;
}
else
{
printf("经过%d次查找,查找到数据%d.\n",i,data);
return;
}
}
printf("经过%d次查找,未能查找到数据%d.\n",i,data);
}
void Sort(int *fp,int length)
{
printf("现在开始为数组排序,排列结果将是从小到大.\n");
int temp;
for(int i=0;i<length;i++)
for(int j=0;j<length-i-1;j++)
if(fp[j]>fp[j+1])
{
temp=fp[j];
fp[j]=fp[j+1];
fp[j+1]=temp;
}
printf("排序完成!\n下面输出排序后的数组:\n");
for(int k=0;k<length;k++)
{
printf("%5d",fp[k]);
}
printf("\n");
}
我粗略的测试了下,没有什么问题,有问题的话可以百度给我留言,当然,程序很容易,你可以自己修改。