forked from Annex5061/java-algorithms
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.cpp
More file actions
Latest commit
26 lines (25 loc) · 662 Bytes
/
Copy pathBinarySearch.cpp
File metadata and controls
26 lines (25 loc) · 662 Bytes
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
#include<bits/stdc++.h>
usingnamespacestd;
intbinarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
returnbinarySearch(arr, l, mid - 1, x);
returnbinarySearch(arr, mid + 1, r, x);
}
return -1;
}
intmain(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return0;
}