linear to binary help

May 11, 2013 at 7:40pm
how would i write this code in to binary search ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
using namespace std;
int lotteryList[10];
int main()
{
const int LOTTERY = 10;
int nums [LOTTERY] = {13579, 26791, 26792,33445, 55555, 62483, 77777, 79422, 85647, 93121 };

int winningNumber;
cout<<"Enter this week's winning number";
cin>>winningNumber;
for(int i=0;i<10;i++)
{
if(nums[i]==winningNumber)
{
cout<<"One of the tickets is a winner this week."<<endl;
break;
}else if(i==9) cout<<"Not one of the tickets is a winner this week."<<endl;
}
system ("pause");
return 0;
}
May 11, 2013 at 7:51pm
set start = 0 and finish = 9. That is the range of elements in the table that you want to search.
A:
Select the middle item of the list. mid = start+finish /2
If found, you are done.
If start == finish you are done and the item was not found.
If the middle item is is greater than the search item, set finish = mid - 1
else set start = mid + 1
repeat from step A.
Last edited on May 11, 2013 at 7:52pm
May 11, 2013 at 8:36pm
im lost could you please use code it for me.. we havent touched on binary search in class yet
May 11, 2013 at 8:54pm
I described the algorithm. In order to code it, you need to understand what it does. Sorry if i didn't explain it very well.
http://en.wikipedia.org/wiki/Binary_search_algorithm
Or here's a video which explains the concepts.
http://youtu.be/wNVCJj642n4
May 13, 2013 at 1:49am
Thank You :)
Topic archived. No new replies allowed.