OK, This is probably a walk in the park for you 1337 C++ programmers, but Im a newbie
. OK, I have to construct a program using fuctions which performs a Binary Search on a 100 element array which contains the first 100 even numbers. Then the program displays how many searches it took to find the number. If the inputed number isn't in the array, then the program will display that the number isn't in the array after X number of tries. I think I have pretty much all of the program finished, except I have no clue how to setup the array w/ the even integers.
Here is my Program so far:
You can also DL the source code here:
http://thesasclan.com/stuff/Binary_Search_v2.cpp
Here is my Program so far:
//Binary Search
#include<iostream.h>
#include<iomanip.h>
void input(int &num,int cont);
void binary_search(int a[100], int hi, int lo, int num, int &cont);
int main()
{
int a[100]; //*************** Here is where I need to fix up the array...
int num;
int cont = 1;
int lo = 0;
int hi = 99;
while (cont == 1)
{
input(num, cont);
binary_search(a, 0, 100, num, cont);
}
return (0);
}
void input (int &num,int cont)
{
if (cont == 1)
{
cout << "Enter the number for which you want to search: ";
cin >> num;
cout << endl;
}
}
void binary_search(int a[100], int lo, int hi, int num, int &cont)
{
int mid;
int count = 1;
mid = (lo + hi) / 2;
while((a[mid] != num) && (lo <= hi))
{
count++;
if(a[mid] > num)
{
hi = mid - 1;
}
else
{
lo = mid + 1;
}
mid = (lo + hi) / 2;
}
if(lo <= hi)
{
cout << "A binary search found the number in ";
cout << count << " comparisons.";
cout << endl;
}
else
{
cout << "Number not found by binary search after ";
cout << count << " comparisons.";
cout << endl;
}
cout << "Would you like to Continue with the Program? (1/0)";
cin >> cont;
cout << endl;
}
You can also DL the source code here:
http://thesasclan.com/stuff/Binary_Search_v2.cpp