Thursday, 24 August 2017

BINARY SEARCH

#include <stdio.h>
int main(void)
{
 int num;
 scanf("%d",&num);
 int a[num];
 int key,i,flag=0,temp;
 for(i=0;i<num;i++)
  scanf("%d",&a[i]);
 scanf("%d",&key);
 int mid=num/2;
 if(a[mid]==key)
 {
  printf("Element found at index %d",mid+1);
  return 0;
 }
 else if(key<a[mid])
 {
for(i=0;i<mid;i++)
{
 if(a[i]==key)
 {
  flag=1;
  temp=i;
 }
}
}
else if(key>a[mid])
{
 for(i=mid+1;i<num;i++)
 {
  if(a[i]==key)
  {
   flag=2;
   temp=i;
  }
 }
}
 if(flag==1)
  printf("Element found at index %d",temp+1);
 else if(flag==2)
  printf("Element found at index %d",temp+1);
 else
  printf("Element not found");
 return 0;
}

No comments:

Post a Comment