-
Notifications
You must be signed in to change notification settings - Fork 0
/
b+tree.cpp
133 lines (117 loc) · 3.08 KB
/
b+tree.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include<bits/stdc++.h>
using namespace std;
struct Bucket
{
int order=0;
int ld=0;
vector<int> v;
};
int gd,cap,oc=0;
map<int,Bucket *> mp;
class Hash{
public:
Hash(int gd){
{
for(int i=0; i<(1<<gd); i++){
Bucket * nb = new Bucket;
nb->ld=gd;
nb->order=oc++;
mp[i]=nb;
}
}
cout << "a extendible HASH MAP with global depth "<< gd << " is created." << endl;
}
void insert(int val){
int tr=val%(1<<gd);
if(mp[tr]->v.size()<cap){
mp[tr]->v.push_back(val);
}
else{
//cout<<val<<" ";
extend(tr);
insert(val);
}
}
bool search(int val){
int tr=val%(1<<gd);
if(mp[tr]->v.end()==find(mp[tr]->v.begin(), mp[tr]->v.end(), val)) return false;
else return true;
}
void extend(int tr){
Bucket * nb = new Bucket;
nb->order=oc++;
vector<int> temp;
temp=mp[tr]->v;
mp[tr]->v.clear();
if(mp[tr]->ld==gd){
gd++;
//cout<<tr<<" "<<gd<<" ";
mp[tr]->ld=gd;
nb->ld=gd;
mp[tr^(1<<(gd-1))]=nb;
for(int i=0; i<(1<<(gd-1)); i++){
if(i!=tr){
mp[i^(1<<(gd-1))]=mp[i];
}
}
for(int i=0; i<temp.size(); i++)
{
int ad=temp[i]%(1<<gd);
mp[ad]->v.push_back(temp[i]);
}
}
else{
mp[tr]->ld++;
mp[tr^(1<<(mp[tr]->ld-1))]=nb;
nb->ld=mp[tr]->ld;
for(int i=0; i<temp.size(); i++){
int ad=temp[i]%(1<<(nb->ld));
mp[ad]->v.push_back(temp[i]);
}
}
}
void Delete(int val){
int tr=val%(1<<gd);
mp[tr]->v.erase(find(mp[tr]->v.begin(), mp[tr]->v.end(), val));
}
void display(){
{
cout << gd <<endl;
cout<< oc <<endl;
for(int i=0; i<oc; i++){
for (auto itr = mp.begin(); itr != mp.end(); ++itr) if(itr->second->order==i){
cout<<itr->second->v.size()<<" "<<itr->second->ld<<endl;
break;
}
}
}
}
};
int main(){
int in,val;
cin>>gd>>cap;
Hash ab(gd);
//ab.intial(gd);
while(cin>>in){
//cout<<"2: Insert new value '/n' 3: Search a value '/n' 4: Delete a value '/n' 5: Display status of the hash table '/n' 6: Quit";
if(in==2){
cin >> val;
ab.insert(val);
}
else if(in==3){
cin >> val;
if(ab.search(val)) cout<< "value '"<<val<< "' is present."<<endl;
else cout<< "element not found"<<endl;
}
else if(in==4){
cin>>val;
if(ab.search(val)) ab.Delete(val);
else cout<< "element not found"<<endl;
}
else if(in==5){
ab.display();
}
else if(in==6) break;
}
return 0;
}