-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBS.cpp
More file actions
69 lines (65 loc) · 1.46 KB
/
Copy pathBS.cpp
File metadata and controls
69 lines (65 loc) · 1.46 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Binary Search using Recursion
#include <iostream>
#include <algorithm>
using namespace std;
// function to search recursively
void binary(int l[], int low, int high, int x)
{
int mid;
mid = (low+high)/2;
if(low <= high)
{
if(l[mid] < x) // search element is greater than mid element
{
low = mid+1;
binary(l,low,high,x);
}
else if(l[mid] == x) // search element is equal to mid element
{
cout<<x<<" is present in the array "<<endl; // element found
}
else // search element is smaller than mid element
{
high = mid-1;
binary(l,low,high,x);
}
}
else
{
cout<<x<<" is not present in the array"; // element not found
}
}
int main() // main function
{
int x, n;
int l[40];
int low, high;
low=0;
cout<<"Enter the size of array: "; // input size of array
cin>>n;
high=n-1;
cout<<"Enter the elements of array: "<<endl; // input array
for (int i=0; i<n; i++)
{
cin>>l[i];
}
sort(l,l+n); // sort the array elements
cout<<"Enter the element to search: "; // input element to search
cin>>x;
binary(l,low,high,x); // calling function to search
return 0;
}
/*
-------------OUTPUT-------------
Enter the size of array: 5
Enter the elements of array:
1 5 4 3 2
Enter the element to search: 3
3 is present in the array
--------------------------------
Enter the size of array: 6
Enter the elements of array:
1 4 5 8 7 3
Enter the element to search: 9
9 is not present in the array
*/