Hi everyone,
I'm trying to brush up on my C and basic algorithms.
I just wrote a program to perform binary search and every time I run it, I get a segmentation fault that I just don't understand where it is coming from. I actually wrote a program to perform linear search using the same main function as the binary search program and it seems to work fine, but for some reason binary search always fails.
Would someone be able to point out to me what is going on to cause this? An explanation along with it would be awesome and greatly appreciated. Thank you!
Here is the code for linear search that works just fine:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 20
int linear_search(int [], int, int);
int main()
{
int arr[SIZE], i, x;
int n = sizeof(arr)/sizeof(arr[0]);
srand(time(0));
for (i = 0; i < n - 1; i++)
{
arr[i] = rand() % 31;
}
printf("\nEnter the number to search for (0 - 31): ");
scanf("%d", &x);
int result = linear_search(arr, n - 1, x);
(result == -1) ? printf("\nElement is not present in array") : printf("\nElement is present at index %d.", result);
for (i = 0; i < n - 1; i++)
{
printf("\n\narr[%d] = %d", i, arr[i]);
}
return 0;
}
int linear_search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
{
if (arr[i] == x)
return i;
}
return -1;
}
And here is the code for binary search that causes a segmentation fault:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 20
int binary_search(int [], int, int, int);
int main()
{
int arr[SIZE], i, x;
int n = sizeof(arr)/sizeof(arr[0]);
srand(time(0));
for (i = 0; i < n - 1; i++)
{
arr[i] = rand() % 31;
}
printf("\nEnter the number to search for (0 - 30): ");
scanf("%d", &x);
int result = binary_search(arr, 0, n - 1, x);
(result == -1) ? printf("\nElement is not present in array") : printf("\nElement is present at index %d.", result);
for (i = 0; i < n - 1; i++)
{
printf("\n\narr[%d] = %d", i, arr[i]);
}
return 0;
}
int binary_search(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = 1 + (r - 1) / 2;
if (arr[mid] == x) return mid;
if (arr[mid] > x) return binary_search(arr, l, mid - 1, x);
return binary_search(arr, mid + 1, r, x);
}
return -1;
}