BINARY SEARCH IN C LANGUAGE
#include<stdio.h>
int binary(int arr[],int size,int element){
int low,high,mid;
low=0;
high=size-1;
while(low<=high){
mid = (low+high)/2;
if(arr[mid]==element){
return mid+1;
}
if(arr[mid]<element){
low=mid+1;
}
else{
high=mid-1;
}
}
return -1;
}
int main()
{
int size,arr[size],element;
printf("please enter the size of array\n");
scanf("%d",&size);
printf("enter the sorted elements for the array \n");
for(int i=0;i<size;i++){
scanf("%d",&arr[i]);
}
printf("enter the elment to be searched in the array \n");
scanf("%d",&element);
int index = binary(arr,size,element);
printf("the element %d is found at index %d \n",element,index);
return 0;
}
0 Comments