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 54 55 56 57 58 59 60 61 62
|
#include <iostream>
#include <cmath>
using namespace std;
// the function
int binarySearch(int L[],int x, int first, int last)
{
if (last >= first) //first > last)
{
//return -1;
int middle = (first + last) / 2;
if (x == L[middle])
return middle;
else if (x < L[middle])
return binarySearch(L, x, first, middle - 1);
else //if(x > L[middle])
return binarySearch(L, x, middle + 1, last);
}
else
return -1;//(first + 1); // failed to find key
}
int main()
{
/* int myList[size] = n;
int myfirst = 0;
int mylast = n - 1;
int findthis;*/
int myList[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
//int size;
//int myList[size];
//int n = myList[10];
int myfirst = 0;
int mylast = 10;//n - 1;
int findthis;
//int i = 0;
cout << "Please enter a number to find: " << endl;
cin >> findthis;
int resultloc = binarySearch(myList, findthis, myfirst, mylast);
if ( resultloc == -1 )
{
cout << "number not found" <<endl;
}
else
{
cout <<" number is found in position " << resultloc + 1 << endl;//binarySearch(myList, findthis, myfirst, mylast) <<endl;
}
/*if(resultloc == middle)
{
cout << findthis << " was found in position " << middle << endl;
}*/
return 0;
}
|