1#include<iostream>
2using namespace std;
3int binarySearch(int arr[], int p, int r, int num) {
4 if (p <= r) {
5 int mid = (p + r)/2;
6 if (arr[mid] == num)
7 return mid ;
8 if (arr[mid] > num)
9 return binarySearch(arr, p, mid-1, num);
10 if (arr[mid] < num)
11 return binarySearch(arr, mid+1, r, num);
12 }
13 return -1;
14}
15int main(void) {
16 int arr[] = {1, 3, 7, 15, 18, 20, 25, 33, 36, 40};
17 int n = sizeof(arr)/ sizeof(arr[0]);
18 int num = 33;
19 int index = binarySearch (arr, 0, n-1, num);
20 if(index == -1)
21 cout<< num <<" is not present in the array";
22 else
23 cout<< num <<" is present at index "<< index <<" in the array";
24 return 0;
25}
1using namespace std;
2
3// A recursive binary search function. It returns
4// location of x in given array arr[l..r] is present,
5// otherwise -1
6int binarySearch(int arr[], int l, int r, int x)
7{
8 if (r >= l) {
9 int mid = l + (r - l) / 2;
10
11 // If the element is present at the middle
12 // itself
13 if (arr[mid] == x)
14 return mid;
15
16 // If element is smaller than mid, then
17 // it can only be present in left subarray
18 if (arr[mid] > x)
19 return binarySearch(arr, l, mid - 1, x);
20
21 // Else the element can only be present
22 // in right subarray
23 return binarySearch(arr, mid + 1, r, x);
24 }
25
26 // We reach here when element is not
27 // present in array
28 return -1;
29}
30
31int main(void)
32{
33 int arr[] = { 2, 3, 4, 10, 40 };
34 int x = 10;
35 int n = sizeof(arr) / sizeof(arr[0]);
36 int result = binarySearch(arr, 0, n - 1, x);
37 (result == -1) ? cout << "Element is not present in array"
38 : cout << "Element is present at index " << result;
39 return 0;
40}