Saturday, January 14, 2012

Searching Algorithm : Binary Search

Recursive Binary Search ::
    #include<stdio.h>
#include<stdlib.h>

int binary_search(int a[],int value,int left,int right)
{
if(right<left)return -1;
int mid = (left+right)/2;
if(a[mid]==value)return mid;
if(value<a[mid])binary_search(a,value,left,mid-1);
else binary_search(a,value,mid+1,right);
}

int main()
{
int i,n,m,a[100],left,right,value;
while(scanf("%d",&n)==1 && n)
{
for(i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&value);

left = 0;
right = n;
m = binary_search(a,value,left,right);
if(m==-1) printf("Not Found\n");
else  printf("Found at %d\n",m);
}
return 0;
}

############################################################################## 


#include<stdio.h>
#include<algorithm>
using namespace std;


int Data[10000];
int Binary_Search(int data[],int LB,int UB,int val)
{
    int Beg,End,Mid;
    Beg = LB;End = UB;Mid = (int)(Beg+End)/2;


    while( Beg <= End && Data[Mid] != val)
    {
        if(val < Data[Mid])End = Mid - 1;
        else Beg = Mid + 1;


        Mid = (int)(Beg+End)/2;
    }
    if(Data[Mid] == val)
        return Mid;
     return -1;
}
int main()
{
    int i,n,val,res;
    while(scanf("%d",&n)==1)
    {
        for(i=0;i<n;i++)
        {
            scanf("%d",&Data[i]);
        }
        sort(Data,Data+n);
        scanf("%d",&val);
        res = Binary_Search(Data,0,n-1,val);
        printf("%d\n",res);
    }
    return 0;
}



4 comments:

  1. This is wrong. Consider the array [1] and search for the value 2.
    left = 0, right = n = 1
    mid = 0
    left = mid+1 = 1, right = 1
    mid = 1
    a[mid] is out of bounds

    ReplyDelete
  2. Bob: you are right only when array size is 1.But i declared array size more than 1 :)

    ReplyDelete
  3. Okay. But then when n is 1, you only set the first element of the array. So all the elements from index 1 and after are all uninitialized (they could be arbitrary values). The element at index 1 could *happen* to equal the value you are searching for, in which case it would return index 1, which would be incorrect.

    ReplyDelete
  4. opppsssss.....
    just change this line res = Binary_Search(Data,0,n,val);
    to res = Binary_Search(Data,0,n-1,val);

    ReplyDelete