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 86 87 88 89 90
|
#include <iostream>
#include <string>
using namespace std;
int linearSearch(int [], int, int);
int binarySearch(const int[], int, int);
const int SIZE = 10;
int main()
// variables
{
const int lottery = 10;
int options [lottery] = { 13579, 62483, 26791, 77777, 26792, 79422, 33445, 85647, 55555, 93121 };
int lotteryNum;
int location;
//Get the input
cout << "Please enter a five-digit number: " << endl;
cin >> lotteryNum;
location = linearSearch(options, lottery, lotteryNum);
if ( location >-1)
cout << "Congratulations, you have won the lottery!!! " << location << endl;
else
cout << "Sorry, maybe next time. " << endl;
system("PAUSE");
return 0;
}
int linearSearch(int list[], int size, int key)
{
int x;
for (x = 0; x < size; x++)
{
if (list[x] == key)
return 0;
}
return -1;
}
int binarySearch(const int array[], int size, int value);
{
const int lottery = 10;
int options[SIZE] = { 13579, 62483, 26791, 77777, 26792, 79422, 33445, 85647, 55555, 93121 };
int lotteryNum;
int results;
cout << "Please enter a five digit number: " << endl;
cin >> lotteryNum;
results = binarySearch(options, SIZE, lotteryNum);
if (results == -1)
cout << "Sorry, maybe next time. " << endl;
else
{
cout << "Congratulations, you have won the lottery!!! " << endl;
}
system("PAUSE");
return 0;
}
int binarySearch(const int array[], int size, int value)
{
int first = 0,
last = size - 1,
middle,
position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (array[middle] == value)
{
found = true;
position = middle;
}
else if (array[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
|