菜鸡笔记之——二分查找+文件操作
二分查找:
前提是所有数据都已经排好序,将目标值每次跟中间的数mid比较,如果相等可以直接返回,如果比mid大则继续查找大的一边,否则继续查找小的一边。
代码实现(二分查找+读取文件):
文件arctan.txt存放arctan(i)的值,i = 1,2,3,…360,输入一个arctani 的值查出i为多少。
# include <stdio.h>
# include <stdlib.h>
# include <math.h>
# define LEN 361
int main(void)
{
void file_read(char * filename,float *array,int array_len);
int binary_search(float *array,int array_len,float search_number);
float array[361] = {0},y;
char filename[30] = {0};
//read data from the file
printf("which file do you want to read:");
scanf("%s",filename);
file_read(filename,array,LEN);
//binary search
printf("please enter the a float number y (ps:y = arctan(x),x = 1,2,...):\n");
scanf("%f",&y);
int x = binary_search(array,LEN,y);
if (x!=0)
{
printf("arctan%d = %.4f\n",x,y);
}
else
{
printf("can not find this number!\n");
}
return 0;
}
//read file function
void file_read(char * filename,float * array,int array_len)
{
FILE * fp = NULL;
fp = fopen(filename,"r");
if (fp==NULL)
{
printf("file open error!\n");
return;
}
for (int i = 1;i<array_len;i++)
{
fscanf(fp,"%f",array+i);
}
fclose(fp);
}
//binary search
int binary_search(float * array,int array_len,float y)
{
int low = 1,high = array_len-1,mid;
while (low<high)
{
mid = (high+low)/2;
if (fabs(array[mid]-y)<1e-3)
{
return (mid);
}
else if (y<array[mid])
{
high = mid-1;
}
else if (y>array[mid])
{
low = mid+1;
}
}
return 0; //return 0 if can not find the target
}
附:arctan.txt
运行结果: