Answer the question
In order to leave comments, you need to log in
Where does the error come from?
Hello! I wrote a simple algorithm from a book in C.
Binary search algorithm.
But when I decided to check its performance, I met a strange error. If the value of the array length is more than 10,000 (well, the elements there also turn out to be from 1 to 10,000), then when I go beyond these values (that is, I look for the number 10001 or -1 in the array), it starts to give an error: segmentation fault (core dumped). But when the value (and the length of the array and its contents) is up to 10,000, i.e. 1000 or 100, everything works as it should, and if the desired number is not found, then 0 is returned.
Found another error. If length = 2147483647, then the program refuses to work at all.
#include <stdio.h>
#include <stdlib.h>
const unsigned int length = 10000;
int binary_search(int *arr, int item)
{
unsigned int low;
unsigned int high;
unsigned int mid;
int guess;
low = 0;
high = length - 1;
while (low <= high)
{
mid = high + low;
guess = arr[mid];
if (guess > item)
high = mid - 1;
else if (guess < item)
low = mid - 1;
if (guess == item)
return (arr[mid]);
}
return (0);
}
int main(int argc, char **argv)
{
int arr[length];
unsigned int count;
count = 0;
while (count < length)
{
arr[count] = count + 1;
count++;
}
printf("%i", binary_search(arr, atoi(argv[1])));
return (0);
}
Answer the question
In order to leave comments, you need to log in
mid = high + low; guess = arr[mid];
else if (guess < item) low = mid - 1;
int arr[length];
If length = 2147483647, then the program refuses to work at all.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question