forked from adi1998/CSN-102
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearch.cpp
More file actions
38 lines (26 loc) · 840 Bytes
/
search.cpp
File metadata and controls
38 lines (26 loc) · 840 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
27
28
29
30
31
32
33
34
35
36
37
38
#include<iostream>
#include<string>
using namespace std;
int binarySearch(int* inputArr, int element, int low, int high);
int main(){
int *sampleArray = new int[10];
for (int i = 0; i < 10; i++){
sampleArray[i] = i+1;
}
cout << binarySearch(sampleArray, 8, 0, 9);
}
int binarySearch(int* inputArr, int element, int low, int high){
if (low <= high){
if (inputArr[low] == element) return low;
if (inputArr[high] == element) return high;
int mid = low + (high-low)/2;
if (inputArr[mid] == element) return mid;
if (inputArr[mid] < element){
binarySearch(inputArr, element, mid+1, high);
}
else if (inputArr[mid] > element){
binarySearch(inputArr, element, low, mid-1);
}
}
else return -1;
}