Wednesday, February 7, 2018

Binary Search

Binary Search  follow divide and conquer rule.

#include <stdio.h>
 int bSearch(int arr[], int l, int r, int x)
{
   if (r >= l)
   {
        int mid = l + (r - l)/2; 
     
        if (arr[mid] == x)     
            return mid;

        if (arr[mid] > x)
            return bSearch(arr, l, mid-1, x);

     
        return bSearch(arr, mid+1, r, x);
   }

   return -1;
}

int main(void)
{
   int n,c,x;
   int arr[100] ;
   scanf("%d",&n);
    printf("loop %d" ,n);
 
   for (c = 0; c < n; c++){
    scanf("%d",&arr[c]);
 
   }
 
 scanf("%d",&x); 
 printf("find the number %d" ,x);
 printf("\n");


   int result = bSearch(arr, 0, n-1, x);
   (result == -1)? printf("Not found"): printf("Present index %d",result);
   return 0;
}

No comments:

Post a Comment