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
|
#include <iostream>
using namespace std;
void binarysearch (const int sortedlist[], int firsty, int lasty, int value);
int main( ) {
int list[10] = {13,16,30,42,63,69,78,84,100,200};
int element;
int middle;
int first;
int last;
for( int i = 0; i < 10; i++){
cout <<"[" << list[i] << "] ";
}
middle = 0+9/2;
cout << endl <<"Please enter number to be searched: ";
cin >> element;
if(list[middle] < element){
first = middle+1;
last = 10;
binarysearch(list, first, last, element);
}
else if(list[middle] > element){
first = 0;
last = middle-1;
binarysearch(list, first, last, element);
}
else{
cout << "Found it" << list[middle];
}
}
void binarysearch (const int sortedlist[], int firsty, int lasty, int value) {
int center;
cout << "Searching.....";
for(int p=firsty; p <= lasty; p++){
cout <<"[" << sortedlist[p] << "] ";
}
cout << endl;
center = firsty+lasty/2;
if(center > value){
//Need help here
binarysearch(sortedlist, firsty, lasty, value);
}
else if (center < value){
//Need help here
binarysearch(sortedlist, firsty, lasty, value);
}
else if(center == value){
cout << "Found it" << value;
}
}
|