-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBS- 2D Array.cpp
More file actions
38 lines (30 loc) · 821 Bytes
/
BS- 2D Array.cpp
File metadata and controls
38 lines (30 loc) · 821 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<array>
using namespace std;
int binarysearch(int arr[][4], int row, int col, int key){
int start= 0;
int end= row*col -1;
// int mid= (start+end)/2;
int mid= start+ (end - start)/2; // if start= 2^31-1, end= 2^31-1
while(start<=end){
int element= arr[mid/col][mid%col];
if(element ==key){
return element;
}
if(key> element){
start= mid+1;
}
else{
end= mid-1;
}
//mid= (start+end)/2;
mid= start+ (end - start)/2;
}
return -1;
}
int main(){
int arr[3][4]= {{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}};
int index= binarysearch(arr, 3, 4, 3);
cout<<"index of 14 is "<<index<<endl;
return 0;
}