#include<conio.h>
#include<stdio.h>
int binary_search(int arr[],int size,int item){
int l=0,h=size-1,loc=-1;
while(l<=h){
int mid=(l+h)/2;
if(arr[mid]==item){
return mid;
}
else if(arr[mid]>item){
h=mid-1;
}
else{
l=mid+1;
}
}
return loc=-1;
}
int main(){
int size,search,item,i,arr[50];
int a=1;
printf("Enter the size of array : ");
scanf("%d",&size);
printf("\nEnter the elements for the array with spaces : ");
for(i=0;i<size;i++){
scanf("%d",&arr[i]);
}
do{
printf("\nEnter the searchable term :");
scanf("%d",&item);
search=binary_search(arr,size,item);
if(search==-1){
printf("No element found !\n");
}
else{
printf("\nElement found at index : %d ",search);
}
printf("\nEnter -1 to stop : ");
scanf("%d",&a);
}while(a!=-1);
getch();
return 0;
}
0 Comments
Thanks for the valuable feedback 😀