Doing a coding exercise for school, where we have to utilize binary search to find the location of a value within an array. The output should generate the index location.
When testing it out it's very "hit and miss". Sometimes it will say when a value is there, other times when a value is clearly there it will come up with "Element is not present in array". Struggling to troubleshoot where the source of this inconsistency is coming from.
Any help/tips/advice would be greatly appreciated.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define SIZE 10
int binarySearch(int array[], int starting, int ending, int searchKey)
{
if (ending >= starting)
{
int mid = starting + (ending - starting)/2;
if (array[mid] == searchKey) return mid;
if (array[mid] > searchKey) return binarySearch(array, starting, mid-1, searchKey);
return binarySearch(array, mid+1, ending, searchKey);
}
return -1;
}
int main(void)
{
int array[10],i;
int searchKey;
srand(time(NULL));
for (i=0; i<10; i++)
array[i]=rand()%100;
printf("Array before sorting \n");
for (i=0; i<10; i++)
printf("%d \n", array[i]);
printf("Enter a number to search\n");
scanf("%d", &searchKey);
int result = binarySearch(array, 0, SIZE-1, searchKey);
(result == -1)?
//Displaying the results to the user
printf("Element is not present in array")
: printf("Element is present at index %d", result+1);
return 0;
}
Binary search requires that the array is sorted.
It says:
In computer science, binary search, also known as ...., is a search algorithm that finds the position of a target value within a sorted array.
You generate the array by doing:
for (i=0; i<10; i++)
array[i]=rand()%100;
so it's obviously not a sorted array. Consequently binary search will not work.
You can use qsort
on the array to sort it. If your not allow to change the array, you'll need another search-algorithm than binary search.