problem to search an element in an array containing following elements 12,15,20,35,40 using binary search where search element ele=40
Answers
Note: I am using C programming language
Codes:
#include<stdio.h>
int BinarySearch(int A[],int lb,int ub,int n);
int main(){
int ub,lb;
int array[20];
int x,y,n,i;
printf("\n * Enter the no of elements in the array (max. 20): ");
scanf("%d",&n);
printf("\n * Enter the array elements (in Ascending order): \n");
for(i=0;i<n;i++){
scanf("%d",&array[i]);
}
printf("* Enter the number to be searched: ");
scanf("%d",&x);
y = BinarySearch(array,0,6,x);
if(y<0){
printf("\n ** Data not found.\n\n");
}
else{
printf("\n ** Data found at position: %d \n\n ",y+1);
}
return 0;
}
int BinarySearch(int A[],int lb,int ub,int n){
int x;
int mid;
mid = (lb+ub)/2;
if(lb<=ub){
if(A[mid]==n){
return mid;
}
else if(A[mid]<n){
lb = mid + 1;
x =BinarySearch(A,lb,ub,n);
}
else if(A[mid]>n){
ub = mid - 1;
x =BinarySearch(A,lb,ub,n);
}
}
else{
return -1;
}
}
**Please mark this as Brainliest answer!