1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
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();
}
| |