question on binary search

kindly guide me through the errors in the following code

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
  #include <iostream>
using namespace std;
int main()
{
    int n,num;
    int arr[50];
    cout<<"Enter the no. of elements of array"<<endl;
    cin>>n;
    cout<<"Enter the elements of array"<<endl;
    for(int i=0;i<n;i++)
    { 
        cin>>arr[i];
    }
    int beg=0;
    int endd=n-1;
    int mid=(beg+endd)/2;
    cout<<"Enter the element you want to search"<<endl;
    cin>>num;
    while(num!=arr[mid])
    {
        for(;;num!=arr[mid])
        {
            if(num<arr[mid])
            {
                endd=mid-1;
                mid=(endd+beg)/2;
            }
            else if(num>arr[mid])
            {
                beg=mid+1;
                mid=(endd+beg)/2;
            }
        }
        if(num==arr[mid])
        {
            cout<<"Search Successful"<<endl;
            break;
        }
    }
}

Firstly you need to ensure that the elements are sorted.
Secondly, I would suggest that you read up on a binary search. Wikipedia has a good iterative version you could translate into C++. http://en.wikipedia.org/wiki/Binary_search_algorithm#Iterative

Hope it helps.
Topic archived. No new replies allowed.