Advertisement
Waliullah8328

Binary_Search

Jun 23rd, 2021
753
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.83 KB | None | 0 0
  1. #include<stdio.h>
  2.  
  3.  int Binary_Search(int a[],int n,int x)
  4.  {
  5.      int left,right,mid;
  6.      left = 0;
  7.      right = n-1;
  8.   while(left <= right)
  9.   {
  10.       mid = (left + right)/2;
  11.  
  12.           if( x == a[mid])
  13.           {
  14.               return mid;
  15.           }
  16.           if(x < a[mid])
  17.           {
  18.             right = mid - 1;
  19.           }
  20.           else
  21.           {
  22.               left = mid + 1;
  23.           }
  24.  
  25.   }
  26.      return -1;
  27.  }
  28. int main()
  29. {
  30.   int a[30],n,x,i;
  31.   printf("Enter how many input you insert : ");
  32.   scanf("%d",&n);
  33.   printf("Input your %d Numbers : \n",n);
  34.   for(i=0;i<n;i++)
  35.   {
  36.      scanf("%d",&a[i]);
  37.   }
  38.   printf("Which number you want to search : ");
  39.   scanf("%d",&x);
  40.  if(Binary_Search(a,n,x) == -1)
  41.  {
  42.  
  43.      printf("Not Found\n");
  44.  }
  45.  else printf("Found in index of %d",Binary_Search(a,n,x));
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement