在这个 C 程序中,我正在对作为 data.txt 读入的数组进行二进制搜索
首先,我尝试将 data.txt 作为数组扫描。其次,我使用插入排序算法对其进行排序。第三,我正在对数组进行二进制搜索。我是 C 新手,我不知道我的代码哪里出了问题,感谢您帮助我知道我做错了什么。
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int main ()
{
int v, t, low, high, mid, search;
int n = 20, array[20];
int p = 0;
FILE *infile;
infile = fopen(“data.txt”,”r”);
while(!feof(infile))
{
fscanf(infile,”%d”, &array[p]);
p++;
}
for (p = 0; p < n; p++) {
scanf("%d", &array[p]);
}
for (p = 1 ; p <= n - 1; p++) {
v = p;
while ( v > 0 && array[v] < array[v-1]) {
t = array[v];
array[v] = array[v-1];
array[v-1] = t;
v--;
}
}
for (p = 0; p <= n - 1; p++) {
printf("%d\n", array[p]);
printf("Please enter a value (-1 = done)>\n");
scanf("%d",&search);
low = 0;
high = n - 1;
mid = (low+high)/2;
while( low <= high )
{
if ( array[mid] < search )
low = mid + 1;
else if ( array[mid] == search )
{
printf("%d is located at %d in the array.\n", search, mid+1);
break;
}
else
high = mid - 1;
mid = (low + high)/2;
}
if ( low > high )
printf("-1\n");
return 0;
}