Can someone please have a look and help me on making this Binary Search algorithm work. Donmt know what is wrong with it .
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
enum SearchResult {FOUND, NOT_FOUND};
SearchResult binarySearch(int array[], int key, int low, int high, int *comparisons);
void fill_array(int array[], int sizeOfData);
const int RANGE = 200; // random data used in range 0-199
int main()
{
const int arraySize = 100;
int a[arraySize];
FILE *resultsFile;
resultsFile = fopen("bsrch.dat", "w"); // open the file lsrrch.dat for writing ("w")
if (resultsFile != NULL) // file successfully opened
{
// seed the random number generator so it gives different
// random numbers each time
srand ( time (0) );
// Table headings
printf ("Found\t Data Size\t Comparisons Needed\n" );
//\t puts in a tab character, \n a new line
fprintf (resultsFile, "Data Size\t Comparisons Needed\n" );
fill_array(a, arraySize);
// Generate table for data of different sizes
// giving number of comparisons each time
for (int datasize = 1; datasize <= arraySize; datasize = datasize + 1)
{
int count = 0; // number of comparisons this time
SearchResult result; // result of this search
int searchKey = rand() % RANGE;
result = binarySearch(a, searchKey, 0, datasize -1, &count);
if (result == FOUND)
printf("KEY FOUND \t");
else
printf("NOT FOUND \t");
// print results in a table
printf("%d \t\t\t %d\n", datasize, count);
fprintf(resultsFile, "%d \t\t\t %d\n", datasize, count);
}
}
else
fprintf(resultsFile, "File not opened\n");
fclose(resultsFile); return 0;
}
// generate data in range 0-200 by doubling position and fill the
// array with it up to the given size
void fill_array(int array[], int sizeOfData)
{
for (int counter = 0; counter < sizeOfData; counter++)
{
array[counter] = counter * 2;
}
}
// A binary search function that returns the number of comparisons
// made call by value as well as a direct indication of found or not.
SearchResult binarySearch(int array[], int key, int low, int high, int * comparisons)
{
int mid;
*comparisons = *comparisons + 1; //about to do a comparison
if (low > high) return NOT_FOUND;
mid = (low + high) / 2;
if (array[mid] == key)
return FOUND; // Key found!
else if (key < array[mid])
return binarySearch(array, key, low, mid-1, comparisons);
else
return binarySearch(array, key, mid+1, high, comparisons);
}