-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortedArray.cpp
More file actions
88 lines (77 loc) · 1.33 KB
/
Copy pathSortedArray.cpp
File metadata and controls
88 lines (77 loc) · 1.33 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include "SortedArray.h"
#include <algorithm>
using namespace std;
template<class T>
SortedArray<T>::SortedArray()
{
data = new vector<T>();
}
template<class T>
SortedArray<T>::~SortedArray()
{
delete data;
}
template<class T>
void SortedArray<T>::ReSort()
{
sort(data->begin(), data->end());
}
template<class T>
T& SortedArray<T>::operator[](int i)
{
return (*data)[i];
}
template<class T>
const T& SortedArray<T>::operator[](int i) const
{
return data->at(i);
}
template<class T>
void SortedArray<T>::Insert(const T& elem)
{
int l = 0, r = size - 1;
int target = -1;
while (l <= r)
{
int mid = (l + r) >> 1;
if (data->at(mid) >= elem)
{
target = mid;
r = mid - 1;
}
else
{
l = mid + 1;
}
}
if (target == -1) data->push_back(elem);
else data->insert(data->begin() + target, elem);
++size;
}
template<class T>
void SortedArray<T>::Erase(int index)
{
data->erase(data->begin() + index);
--size;
}
template<class T>
void SortedArray<T>::Erase(const T& elem)
{
int l = 0, r = size - 1;
int target = -1;
while (l <= r)
{
int mid = (l + r) >> 1;
if (data->at(mid) >= elem)
{
target = mid;
r = mid - 1;
}
else
{
l = mid + 1;
}
}
if (data->at(target) == elem) data->erase(data->begin() + target);
--size;
}