Binary Search

closed account (G60iz8AR)
How to find the binary search with these numbers 1 6 9 10 12 31 36 50 68 73 77 78 80 82 83 84 85 89 94 98 ? PLEASE HELP
#include <fstream>
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

const int MAX = 30;
const int NOT_FOUND = -1;

void loadArray( int a[], int &cnt, ifstream &infile );
void printArray( int a[], int cnt );
int bsearch( int a[], int cnt, int target );

int main( int argc, char**argv )
{
ifstream infile;
infile.open( argv[1], ios::in );
if (!infile) exit(0);

int arr[MAX];
int cnt=0;

loadArray( arr, cnt, infile );
printArray( arr, cnt );

int target=-1;
do
{
cout << "number to search for? ";
cin >> target;
if ( target == -1 ) break;
int pos = bsearch( arr, cnt, target );
if (pos = NOT_FOUND )
cout << target << " not found\n";
else
cout << target << " found at position " << pos << endl;
}
while ( true );


return 0;
} // END MAIN

//####################################################################

void loadArray( int a[], int &cnt, ifstream &infile )
{
while( cnt < MAX && infile >> a[cnt] )
cnt++;
infile.close(); // Done reading. Close it
}
void printArray( int a[], int cnt )
{
for ( int i=0 ; i<cnt ; i++ )
cout << a[i] << " ";
cout << endl;
}
int bsearch( int a[], int cnt, int target )
{
int lo=0, hi=cnt-1;
while ( lo <= hi )
{
int mid = (lo+hi)/2;

/* if the target # is here at the mid slot
then just return mid. we are done :)

otherwise if target is > a[mid]
set lo to mid+1

otherwise it must be true that target < a[mid]
so, set hi to mid -1
*/
}

// if you make it to here and never returned out of the loop
// then the number must not be in the array
// return NOT_FOUND


return NOT_FOUND; // change as needed
}
insert cout for hi, lo and mid into your loop to find out why it goes wrong.
Topic archived. No new replies allowed.