Function For Binary Search
#include <stdio.h>
int binarySearch(int arr[], int size, int element, int low, int high)
{
int mid;
while (low <= high)
{
if (arr[mid] == element)
{
return mid;
}
if (element < arr[mid]) //element is on the left side
{
high = mid - 1;
}
else
{
low = mid + 1; //element is on the right side
}
}
return -1;
}
Main Program Starts Here
int main()
{
int arr[] = {1, 5, 10, 16, 24, 30, 50, 100};
int size = sizeof(arr) / sizeof(int);
int element = 10;
int low = 0;
int high = size - 1;
int search = binarySearch(arr, size, element, low, high);
so, my problem is that it's not printing this line and in the first place, the compiler is not executing the program. Whenever I try to execute it my pc gets hang
printf("The element %d was found at index %d", element, search);
return 0;
}
Your problem is that you forgot to declare initializes/defines mid
, which will lead to undefined behavior (after that, anything can happened to your program). You'll also need to recalculate mid
every time the loop runs.
Also, as @DavidC.Rankin mentioned below, your sizeArr
parameter is quite unnecessary.
Modified code:
#include <stdio.h>
int binarySearch(int arr[], int element, int low, int high)
{
int mid; //declare here
while (low <= high)
{
mid = (low+high)/2; //recalculate here
if (arr[mid] == element)
{
return mid;
}
else if (element < arr[mid]) //element is on the left side
{
high = mid - 1;
}
else
{
low = mid + 1; //element is on the right side
}
}
return -1;
}
int main()
{
int arr[] = {1, 5, 10, 16, 24, 30, 50, 100};
int sizeArr = sizeof(arr) / sizeof(int);
int element = 10;
int low = 0;
int high = sizeArr - 1;
int searchResult = binarySearch(arr, sizeArr, element, low, high);
printf("The element %d was found at index %d", element, searchResult);
return 0;
}
Result : The element 10 was found at index 2
Noted that keywords such as search
or size
shouldn't be used as variable names.