-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSALdict.cpp
More file actions
67 lines (61 loc) · 1.2 KB
/
SALdict.cpp
File metadata and controls
67 lines (61 loc) · 1.2 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
58
59
60
61
62
63
64
65
66
67
//Dictionary implementation with a sorted array-based list
template <typename Key, typename E>
class SALdict : public Dictionary<Key,E>
{
private:
SAList<Key,E>* list;
public:
SALdict(int size=defaultSize)
{
list = new SAList<Key,E>(size);
}
~SALdict()
{
delete list;
}
void clear()
{
list->clear();
}
//insert an element: keep elements aorted
void insert(const Key& k, const E& e)
{
KVpair<Key,E> temp(k,e);
list->insert(temp);
}
//use binary search to find the element to remove
E remove(const Key& k)
{
E temp = find(k);
if (temp != NULL) list->remove();
return temp;
}
E removeAny()
{
Assert(size() != 0, "Dictionary is empty");
list->moveToEnd();
list->prev();
KVpair<Key,E> e = list->remove();
return e.value();
}
//find "k" using binary search
E find(const Key& k) const
{
int l = -1;
int r = list->length();
while (l+1 != r)
{
int i=(l+r)/2;
list->moveToPos(i);
KVpair<Key,E> temp = list->getValue(0;
if (k < temp.key()) r=i;
if (k == temp.key()) return temp.value();
if (k > temp.key()) l=i;
}
return NULL;
}
int size()
{
return list->length();
}
};