I have been trying to figure this out all day and cannot seem to make it work. Why does my binary search work if I input the array length in manually but when I swap the manual input for:
int max = sizeof(list)/sizeof(list[0]);
it doesn't seem to work. For instance if I try to search for a 2 in a 11 element array of 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 it can't find 2. But if I change int min = 11. It can find 2. Here is the function binary sort:
int binarysearch(int *list, int sfor)
int min = 0;
int max = 10;
int mid = (min + max)/2;
while(min <= max)
{
if (sfor == list[mid])
{
printf("The number you are searching for is in %i place \n", mid + 1);
return 0;
}
else if (sfor < list[mid])
{
max = mid - 1;
}
else
{
min = mid + 1;
}
mid = (min + max)/2;
}
printf("Could not find number! \n");
return 1;
int main(int argc, string argv[]) // number searching for is passed through
{ // command line argument
printf("How many numbers did you want to search through? \n");
int a = GetInt(); //int a is how big should the array of numbers be
printf("What are they: \n");
int i = 0;
int b[a];
for (i = 0; i < a; i++)
{
b[i] = GetInt(); //cycles though each int of the array
}
int x = atoi(argv[1]); //converts command line argument to an int
binarysearch(b, x);
}
Will greatly appreciate any help.