I am rather new to programming and I've run into an issue. I am trying to implement a binary search to an array of 100 random integers. I have them sorted into descending order. However, I cannot get the search to work, I believe I may not fully understand it, (missed that day in class, no notes, working off the internet). Any help would be greatly appreciated. I've given 2 fcns. The binary and the fcn I am calling it in. Sorry if there is to much code.
int binary_search(int random[], int low, int high, int search)
{
int index;
if (low > high)
index = -1;
else
{
int mid = (low + high) / 2;
if (search == random[mid])
index = mid;
else
if (search < random[mid])
index = binary_search(random, low, mid - 1, search);
else
index = binary_search(random, mid + 1, high, search);
} // end if
return index;
}// end binarySearch
int randomizer(int random[]){
srand((unsigned)time(NULL));
ofstream PRINT("P4Output.txt");
const int arraySize = 100; //size of the array
int high = 100; // high for random numbers
int low = -100; // low for random numbers
int size = 0;
int out = 0;
random[arraySize]; // giving the array random 100 elements
int first = 0;
int last = 0;
int index = 0;
int search = 0;
cout << endl << " RANDOM: " << endl;
cout << " *************************************************" << endl << endl << endl;
PRINT << endl << " RANDOM: " << endl;
PRINT << " ************************************************" << endl << endl << endl;
for (int i = 0; i < 100; i++){ // Start of loop to insert 100 random values into array
random[i] = rand() % (high - low + 1) + low; //Inserting random values into array
cout << setw(5) << random[i]; // outputs the random integer with spacing.
PRINT << setw(5) << random[i];
if ((i + 1) % 10 == 0) {
cout << endl << endl << endl; // end of print line for set of 10 values
PRINT << endl << endl << endl;
}// end of if statement
} // End for-loop
cout << " SELECTION SORT: " << endl;
cout << " *************************************************" << endl << endl << endl;
PRINT << " SELECTION SORT: " << endl;
PRINT << " ************************************************" << endl << endl << endl;
selectionSort(random, arraySize); // calling selection sort
for (int j = 0; j < arraySize; j++){ // for-loop
cout << setw(5) << random[j]; //outputs integers w/ spacing
if ((j + 1) % 10 == 0){ // sets rows of ten
cout << endl << endl;
}
}// end of for-loop
cout << " BINARY SEARCH " << endl;
cout << " *************************************************" << endl << endl << endl;
PRINT << " BINARY SEARCH " << endl;
PRINT << " *************************************************" << endl << endl << endl;
index = binary_search(random, first, last, search);
for (int i = 0; i < arraySize; i++){
while (search != 101){
cout << "What number would you like to look for?" << endl;
cin >> search;
if (search == index)
cout << "found @" << index;
else
cout << "not found" << endl;
}
}
return out;
}