OK, I had to redo a binary search in which you have to search for 45 in a list of 10 integers. The previous program I was able to get working and it output the correct "Line 5: 45 found at position 3". Not so much with the recursive version. I'm thinking it's something simple/obvious, but I'm not seeing it. Could I please get a little input/advice/help. Thank you to all who graciously posts. Regards.
header.h file
template<class Type>
int binarySearch(const Type list[],Type length, const Type& item){
int first = 0,
last = length - 1,
mid;
bool found = false;
if (first <= last){ // first check to see it it needs to go any further.
return -1;
mid = (first + last) / 2;
if(list[mid] == item) // if found item, 45.. true if so
found = true;
else if (list[mid] > item)
return binarySearch (list, mid -1, item) ; //passing the list, mid, and item - which is 45. for bottom/lowwer list
else
return binarySearch (list, mid + 1,item); //passing the list, mid, and item - which is 45. for top/higher list
/*if(found)
return mid; // just left over from binary part. should not be needed, ( i wouldn't think)
else
return -1;*/
}//end if's
}//end binarySearch
______________________________________________________________________
main.cpp file
#include <iostream>
#include "binarySearch.h"
using namespace std;
int main(){
int intList[] = {2, 16, 34, 45, 53, 56, 69, 70, 75, 96}; // list of 10 integers with 45 in "middle"
int pos;
pos = binarySearch(intList,10,45); // length is 10, item is 45
if(pos != -1)
cout << "Line 5: " << 45
<< " found at position "
<< pos << endl;
else
cout << "Line 7: " << 45
<< " is not in intList " << endl;
cin.sync();
cin.peek();
}