//Nathan Dominguez CSC5 Chapter 8, P.487, #4
//
/*******************************************************************************
*
* Validate an Account Charge with a Binary Search
*_______________________________________________________________________________
* This program searches for a number with both binary and linear
* searches, and outputs how many searches it takes for each.
*_______________________________________________________________________________
* INPUTS:
* win : the number to search for, input by the user.
* numbers : The list of valid numbers.
* index : the content of the current number being checked.
* found : Whether the number has been found.
* first : Start of array.
* middle : Middle of array.
* last : end of array.
* position : The current index being checked.
* OUTPUT:
* numbinarysearch : Amount of binary searches.
* numlinearsearch : Amount of linear searches.
*******************************************************************************/
#include <iostream>
using namespace std;
int main()
{
//decalre variables
int win; //the number
bool found = false; //loosing numbers
int first = 0; //beginning of array
int index; //content of the current number being checked
int middle; //middle of array
int last = 9; //end of array
int numlinearsearch=0; //amount of linear searches
int numbinarysearch=0; //amount of binary searches
int position = -1; //check index
int numbers[10] = {1357, 2671, 2672, 3345, 5555,
6243, 7777, 7922, 8547, 9121};
//INPUT number
cout << "Enter the number to search for: " << endl;
cin >> win;
//LINEAR SEARCH
while (index < 10 && !found)
{
if (win == numbers[index])
{
found = true;
position = index;
}
index++;
numlinearsearch++;
}
found = false;
position = -1;
//
//Binary search
//LOOP - sort numbers and put them in order
while (first < last && !found)
{
middle = (first+last)/2; //calc middle
if(numbers[middle] == win) //success
{
found = true;
position = middle;
}
else if (numbers[middle] > win) //too low
last = middle - 1;
else //too high
last = middle + 1;
numbinarysearch++;
}
cout << "Linear search found the number in " << numlinearsearch;
cout << " searches." << endl;
cout << "Binary search found the number in " << numbinarysearch;
cout << " searches.";
return 0;
}