Binary Search NO errors still not working

This code does not produces any error but it's like not running properly it returns -16464564651 something,Please check

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
#include<iostream>
using namespace std;
int Bsearch(int[],int,int);
int main()
{
    int ar[50] , index , N , ITEM ,i;
    cout << "\nEnter The Number Of ELEMENTS YOU WANT IN THE ARRAY : ";
    cin >> N;
    cout << "\nEnter The Elements IN The ARRAY : ";
    for (i = 0 ; i < N ; ++i)
    {
        cout << endl;
        cin >> ar[i];
    }
    cout << "\nEnter The Element to Be Searched For :";
    cin >> ITEM;
    index = Bsearch(ar,N,ITEM);
    if(index == -1)
        cout << "\nSORRY ELEMENT NOT FOUND!";
        else
        cout << "INDEX : " << index << "  Position : " << index +1 ;
    return 0 ;
}
int Bsearch(int ar[],int size , int item)
{
    int beg,last,mid;
    beg = 0 ; last = mid -1 ;
    while(beg<=last)
    {
        mid = (beg+last) / 2;
        if (item == ar[mid]) return mid;
        else
            if (item > ar[mid])
            beg = mid + 1 ;
        else
            last = mid - 1;
    }
    return -1;
}
AH Shit Resolved It Guys,Line 27
last = mid -1; was wrong
last = size -1; is correct,silly mistake
Last edited on
Topic archived. No new replies allowed.