forked from Anuragcoderealy/Codenewhacktober
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.cpp
36 lines (33 loc) · 1018 Bytes
/
BinarySearch.cpp
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
#include<bits/stdc++.h>
using namespace std;
int binarySearch(int a[], int beg, int end, int val) {
int mid;
if(end >= beg) {
mid = (beg + end)/2;
if(a[mid] == val){
return mid + 1;
}
else if(a[mid] < val) {
return binarySearch(a, mid+1, end, val);
}
else {
return binarySearch(a, beg, mid-1, val);
}
}
return -1;
}
int main() {
int a[] = {11, 14, 25, 30, 40, 41, 52, 57, 70};
int val = 40;
int n = sizeof(a) / sizeof(a[0]);
int res = binarySearch(a, 0, n-1, val);
printf("The elements of the array are - ");
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\nElement to be searched is - %d", val);
if (res == -1)
printf("\nElement is not present in the array");
else
printf("\nElement is present at %d position of array", res);
return 0;
}