Binary Search in array in C++
#include<iostream>
using namespace std;
struct array {
int a[10];
int size;
int length;
};
void display(struct array arr){
cout<<"The Element is ";
for(int i=0; i<arr.length; i++){
cout<<arr.a[i]<<" ";
}
}
int RBS(int arr[], int l, int h, int key){
int mid=0;
if(l<=h){
mid=(l+h)/2;
if(key==arr[mid]){
return mid;
}
else if(key<arr[mid]){
RBS(arr, l, mid-1, key);
}
else{
RBS(arr, mid+1, h, key);
}
}return -1;
}
int binarysearch(struct array arr, int key){
int l,mid, h;
l=0;
h=arr.length-1;
while(l<=h){
mid=(l+h)/2;
if(key==arr.a[mid]){
return mid;
}
else if(key<arr.a[mid]){
h=mid-1;
}
else{
l=mid+1;
}
}
return -1;
}
int main() {
struct array arr;
arr={{1,22,38,4,5,6},10,6};
cout<<RBS(arr.a, 0, arr.length, 6)<<endl;
cout<<binarysearch(arr, 38)<<endl;
display(arr);
return 0;
}
0 Comments