In this C program, I am doing a binary search of an array that I read in as data.txt
First I am trying to scan in the data.txt as an array Second I am using an insertion sort algorithm to sort it Third I am doing a binary search of the array. I am new to C and I have no idea where my code as gone wrong, thank you for any help in letting me know what I am doing incorrect.
#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;
}
1). initialize n with some value 2). after the insertion sort (i guess) there is a printf to print the array. add another braces after the printf. if u dont this program keeps running(unless you enter a char which breaks the prog) but now it may work cause you are returning before it can loop but it is still a major problem..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.