You are on page 1of 2

Umesh Singh Verma (LCS2022052)

Design Analysis of Algorithm – Lab 01 Topic – Implementaion of Binary Search through recusion

Code:
#include <bits/stdc++.h>
using namespace std;
int binarySearch(int A[],int l,int r,int x){
if(l<=r){
int mid = (l+r)/2;
if(A[mid]==x){
return mid;
}else{
if(A[mid]>x){
return binarySearch(A,l,mid-1,x);
}else{
return binarySearch(A,mid+1,r,x);
}
}
}
return -1;
}
int main() {
int n;
cout<<"Enter the size of the array :";
cin>>n;
int A[n];
cout<<"Since binary search can be applied on the sorted array , Please
Enter the indexes in the sorted format"<<endl;
for(int i=0 ;i<n;i++){
cout<<"enter element of index "<<i<<" : ";
cin>>A[i];
}

// in case if the array is not given sorted then


// int size = sizeof(A)/sizeof(A[0]);
// sort(A,A+size);
// this will give the index on the basis of the sorted array

int find;
cout<<"Enter the element which you want to find ";
cin>>find;

int ans = binarySearch(A,0,5,find);


if(ans==-1){
cout<<"Element not found";
}
else{
cout<<"Element is found is at index "<<ans;
}
return 0;
}

Screen shot of the output:

You might also like