对于有序数组的查找来说,折半查找时一种性能卓越的算法。本次程序从文件中读取数据并存到文件中
程序为
#include<stdio.h>
#include<stdlib.h>
int search(int num[],int key,int len);
int main()
{
FILE * fp;
char * pchBuf;
char tmp[5];
int Len,key;
int i,j=0,k=0,nLen=0;
int num[200];
fp=fopen("bs-1.txt","r"); //以只读打开文件
fseek(fp,0,SEEK_END); //将文件指针移到结尾
Len=ftell(fp); //计算文件长度
rewind(fp); //将文件指针移到开头
pchBuf=(char*)malloc(sizeof(char)*Len+1); //在堆里开空间存放文件的内容
if(!pchBuf) //如果没有分配退出
{
printf("内存不够!\n");
exit(0);
}
Len = fread(pchBuf,sizeof(char),Len,fp); //将文件内容放入空间中,并自动调整长度
fclose(fp); //关闭文件
pchBuf[Len] = '\0'; //将字符长结尾附零
for (i=0;i<=Len;i++)
{
tmp[j++]=*(pchBuf+i); //找到字符串开头
if (*(pchBuf+i)==',' ||*(pchBuf+i)=='\0' ) //判断是否遇到逗号和结尾
{
tmp[j] = '\0'; //将子字符串附零
nLen++;
num[k++]=atoi(tmp); //将字符串转化为整形
j=0; //查找下一个字符串
}
}
printf("请输入一个要查找的数");
scanf("%d",&key);
i=search(num,key,nLen);
printf("数的下标是%d",i);
return 0;
}
//二分算法
int search(int num[],int key,int len)
{
int n; //用于返回的数组下标
int begin=0; //开始位置
int end=len-1; //结尾位置
while(begin<=end)
{
n=(begin+end)/2;
if(num[n]==key)
{
return n;
}else if(key<num[n])
{
end=n-1;
}else
{
begin=n+1;
}
}
return 0;
}
文件为bx-1.txt
1,2,3,4,5,6,7,8,9,10,
11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,25,27,28,29,30,
31,32,33,34,35,36,37,38,39,40,
41,42,43,44,45,46,47,48,49,50,
51,52,53,54,55,56,57,58,59,60,
61,62,63,64,65,66,67,68,69,70,
71,72,73,74,75,76,77,78,79,80,
81,82,83,84,85,86,87,88,89,90,
91,92,93,94,95,96,97,98,99,100,
101,102,103,104,105,106,107,108,109,110,
111,112,113,114,115,116,117,118,119,120,
121,122,123,124,125,126,127,128,129,130,
131,132,133,134,135,136,137,138,139,140,
141,142,143,144,145,146,147,148,149,150
本次只是简单二分查找,并从文件中读取,大家看一下,有不对之处,请指出