forked from dubey-harshit/Hacktoberfest-2024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSparse_Search.cpp
More file actions
57 lines (49 loc) · 1.17 KB
/
Sparse_Search.cpp
File metadata and controls
57 lines (49 loc) · 1.17 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include<iostream>
#include<string>
using namespace std;
int Sparse_search(string a[], int n, string key){
int s = 0;
int e = n-1;
while(s<=e){
int mid = (s + e)/2;
int mid_left = mid-1;
int mid_right = mid+1;
if(a[mid]=="")
{
//update our mid to point to a nearest non empty string
while(1){
if(mid_left < s and mid_right > e){
return -1;
}
else if(a[mid_right] != ""){
mid = mid_right;
break;
}
else if(a[mid_left] != ""){
mid = mid_left;
break;
}
mid_left--;
mid_right++;
}
}
else if(a[mid] == key){
return mid;
}
else if(a[mid] > key){
e = mid-1;
}
else{
s = mid+1;
}
}
return -1;
}
int main(){
string a[] = {"ai", "", "", "bat", "", "", "car", "", "", "dog", "", ""};
int n=12;
string f;
cin>>f;
cout<<Sparse_search(a, n, f)<<endl;
return 0;
}