Skip to content

Commit

Permalink
Binary search
Browse files Browse the repository at this point in the history
  • Loading branch information
accodes21 authored May 23, 2022
1 parent a64b871 commit bf2528b
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions binarysearch.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <stdio.h>
int binarysearch(int a[],int x,int low,int high){
while(low<=high){
int mid = low + (high-low)/2;
if(a[mid]==x)
return mid;
if(a[mid]<x)
low = mid+1;
if(a[mid]>x)
high = mid-1;
}
return -1;
}

int main(){
int a[5], i,n,x,j;
printf("enter elements:");
for(i=0;i<5;i++){
scanf("%d",&a[i]);
}


printf("Array is:");
for(i=0;i<5;i++){
printf("%d ",a[i]);
}


printf("\nEnter element to be searched:");
scanf("%d",&x);

n=sizeof(a)/sizeof(a[0]);
j = binarysearch(a,x,0,n);

if(j==-1)
printf("ELEMENT NOT FOUND");
else
printf("Element found at index %d",j);

return 0;
}

0 comments on commit bf2528b

Please sign in to comment.