-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.txt
More file actions
41 lines (29 loc) · 861 Bytes
/
Copy pathbinarysearch.txt
File metadata and controls
41 lines (29 loc) · 861 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
39
40
41
/*
* File: binarysearch.cpp
* Author: hamidsultanzadeh
*
* Created on September 29, 2019, 6:39 PM
*/
#include <iostream>
using namespace std;
pair<int,int> binarySearch(int arr[],int size,int n){
int left=0, right=size-1;
int middle;
while(left <= right){
middle = (left + right) / 2;
if(arr[middle] > n){
right = middle - 1;
} else if(arr[middle] < n){
left = middle + 1;
} else if(arr[middle] == n){
return make_pair(arr[middle],middle+1); // return value and index
}
}
return make_pair(-1,-1);
}
int main(int argc, char** argv) {
int arr[10]={1,3,5,7,9,11,12,14,15,19};
pair<int,int> result = binarySearch(arr,10,3);
cout<<"n : "<<result.first<<endl<<"i : "<<result.second;
return 0;
}