Implementation of Binary Search Using C Programming

Image result for c programming

Implementation of Binary Search Using C Programming

Code:

   #include<stdio.h>
int BinarySearch(int, int ,int *, int);
int main(){
  int first=0, last;
  int a[20],search,s=0,n,i;
  //int j,temp=0;
  printf("Enter the number of elements :\n");
  scanf("%d",&n);
  printf("Enter the elements :\n");
  for(i=0;i<n;i++)
  {
    scanf("%d",&a[i]);
  }
  printf("Enter the element to be searched :\n");
  scanf("%d",&search);
  last=n-1;

  s=BinarySearch(first, last, a, search);
  if(s>0){
  printf("The element %d is in position %d",search,s);
  }
  else{
  printf("The element %d is not present in the array",search);
  }
  return 0;
}

int BinarySearch(int l, int h, int *a, int x)
{
  int mid;
  while(l<=h){
    mid=(l+h)/2;
    if (x==a[mid])
      return mid;
  else if(x<a[mid])
    h=mid-1;
  else if(x>a[mid])
    l=mid+1;
    }
return -1;
}

No comments