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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
#include <iostream> // needed for Cin and Cout
#include <string> // needed for the String class
#include <math.h> // math functions
#include <stdlib.h>
#include <iomanip>
using namespace std;
int binarySearch(const int [], int, int);
const int size = 20;
int main()
{
// variable list
int searchNumber; // the number you are searching for in the array
int intArray [20] = {2, 4, 5, 8, 9, 12, 16, 18, 19, 23, 33, 36, 38, 38, 45, 48, 59, 66, 79, 666};
int results;
cout << "please enter a number to search for: ";
cin >> searchNumber;
results = binarySearch(intArray, size, searchNumber);
if (results == -1)
{
cout << " That number does not exist in the array \n";
else
{
cout << " That number is found at element " << results;
cout << " in the array. \n";
}
return 0;
}
/***************************
* print array
***************************/
for (int x=0; x<20; x++)
{
if(x%5 ==0)
{
cout << "\n";
}
cout << setw(5) << intArray[x];
}
cout << "\n\n";
int binarySearch( int intArray[], int size, int value);
{
int value;
int first = 0; //First Array element
int last = size -1; // Last Array element
int middle; // Mid-point of search
int position = -1; //postion of search
bool found = false; // flag
while (!found && first <= last)
{
middle = (first + last) /2;
if (intArray[middle] == value)
{
found = true;
position = middle;
}
else if (intArray[middle] > value)
last = middle -1;
else
first = middle +1;
}
return position;
}
system("pause");
return 0;
}
|