Take this lottery program and switch the linear search to a binary search to per
ID: 3628879 • Letter: T
Question
Take this lottery program and switch the linear search to a binary search to perform:
#include<iostream>
using namespace std;
const int size=10;
int linearsearch(int array[], int size, int value)
{
for(int i=0; i<size; i++)
if(array[i] == value) return 1;
return = 0'
}
int main()
{
int *numbers;
int N;
int count;
int results;
cout<<"How many lottery tickets were purchased?:";
cin>> N;
numbers= new int[N];
cout<<" Enter winning lottery ticket's numbers... ";
for (count=0; count<N; count++)
{
cout<<"Winning Number Lottery ticket #"<<(count+1)<<": ";
cin>>numbers[count];
}
for (count=0; count<N; count++)
{
cout<<" Enter your lottery number:";
cin>>results;
if (results == 0)
{
cout<<"Quitting Program ";
break;
}
int k=linearsearch(numbers,N,results);
if (k == 1)
cout<<"Winner! ";
else
cout<<"Loser! ";
}
Explanation / Answer
int BinarySearch(int array[], int numElems, int value)
{
int first = 0, last = numElems - 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;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.