回复:(fireleaf)关于二分法查找数值的程序
這段程序是以前得作業,意思是 先讀取test3.dat內得數據排序之后保存在sort.csv文件內 然后利用二分法查找出電話號碼.輸入得是數據文件內得序列號.數據文件test3.dat如附件.
#include <stdio.h>
#include <conio.h>
#include <string.h>
//#include <mem.h>
#include<stdlib.h>
//#define max 300
struct Info
{
int id;
char str[200];
} data[300];
//int search(int q,int start,int end);
int search(int array[],int key,int max);
int main()
{
struct Info tmp;
int i,j,num,query;
int array[300];
char ch;
char *p;
char tel[12];
FILE *fp;
FILE *fo;
fp = fopen("test3.dat","r");
fo = fopen("sort.csv","w");
num = 300;
memset(data, 0, 300*sizeof(struct Info));
for (i = 0; i<300; i++)
{
fscanf(fp, "%d", &data[i].id);
p = data[i].str;
fscanf(fp, "%c",&ch);
while(ch != '\n')
{
*p = ch;
p++;
fscanf(fp, "%c",&ch);
}
*p = '\n';
}
for (i = 0; i < num; i++)
{
for (j = 0; j < num; j++)
{
if (data[i].id > data[j].id)
{
tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
}
}
for (i = 0; i < num; i++)
{
array[i]=data[i].id;
fprintf(fo,"%d%s",data[i].id,data[i].str);
}
fclose(fp);
fclose(fo);
printf("Please Input Query Number:\n");
printf("Input -1 to End Query\n");
scanf("%d",&query);
while(query != -1)
{
int k = search(array,query,300);
if (k == -1)
{
printf("This Id is not exist!\n");
//scanf("%d",&query);
break;
}
p = data[k].str+strlen(data[k].str);
while (*p != ',') p--;
p++;
strcpy(tel,p);
printf("%s",tel);
scanf("%d",&query);
}
return 0;
}
/*int search(int q,int start,int end)
{
int mid = (end + start)/2;
int i;
if ((end - start) < 3)
{
for (i = start; i < end; i++)
if (q == data[i].id) return i;
return -1;
}
else
{
if (q < data[mid].id)
return search(q,mid,end);
else if (q > data[mid].id)
return search(q,start,mid);
else if (q == data[mid].id)
return mid;
}
return 0;
}*/
int search(int array[],int key,int max)
{
int low=0;
int hig=max-1;
int mid=(low+hig)/2;
while(low<=hig)
{
if(array[mid]==key)return mid;
else if(array[mid]<key)
{
hig=mid-1;
}
else
{
low=mid+1;
}
mid=(low+hig)/2;
}
return -1;
}