forked from philona/cppcodes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchRecursiveMethod.cpp
More file actions
46 lines (30 loc) · 1.07 KB
/
BinarySearchRecursiveMethod.cpp
File metadata and controls
46 lines (30 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include<bits/stdc++.h>
using namespace std;
int binarySearchRecursively(int arr[] , int searchElement , int low , int high){
if(low <= high){
int mid = (low + high)/2;
if(arr[mid] == searchElement)
return mid;
if(arr[mid] < searchElement)
return binarySearchRecursively(arr , searchElement , mid + 1 , high) ;
if(arr[mid] > searchElement)
return binarySearchRecursively(arr , searchElement , low , mid - 1) ;
}
return -1;
}
int main(){
int size;
cout<<"Enter total number of elements : ";
cin>>size;
int arr[size] , low = 0 , high = size ;
for(int elementIndex = 0 ; elementIndex < size ; elementIndex++)
cin>>arr[elementIndex];
cout<<"Enter element to be searched: ";
int searchElement;
cin>>searchElement;
if(binarySearchRecursively(arr , searchElement , low , high))
cout<<"Element found at index "<<binarySearchRecursively(arr , searchElement , low , high);
else
cout<<"Element does not exist"<<endl;
return 0;
}