-
Notifications
You must be signed in to change notification settings - Fork 0
/
array.cpp
161 lines (143 loc) · 2.24 KB
/
array.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#include "array.h"
void Array::resize(int new_capacity) {
int* new_arr = new int[new_capacity];
for (size_t i = 0; i < size; i++) {
new_arr[i] = arr[i];
}
delete[] arr;
arr = new_arr;
capacity = new_capacity;
}
Array::Array() {
capacity = 16;
arr = new int[capacity];
size = 0;
if (arr == nullptr)
{
cout << "Memory allocation failed" << endl;
}
}
Array::Array(int len)
{
capacity = 16;
while (len > capacity) {
len *= 2;
capacity = len;
}
arr = new int[capacity];
size = 0;
if (arr == nullptr)
{
cout << "Memory allocation failed" << endl;
}
}
int Array::get_size() {
return size;
}
int Array::get_capacity() {
return capacity;
}
bool Array::is_empty() {
return size == 0;
}
int Array::at(int index) { // getter
if (index < size) {
return arr[index];
}
}
void Array::push(int item) {
if (capacity == size) {
resize(capacity * 2);
}
arr[size++] = item;
}
void Array::insert(int index, int item) {
if (index == size) {
push(item);
}
else {
if (capacity == size) {
resize(capacity * 2);
}
for (int i = size; i > index; i--) {
arr[i] = arr[i - 1];
}
arr[index] = item;
size++;
}
}
void Array::prepend(int item) {
insert(0, item);
}
int Array::pop() {
if (size > 0) {
int item = arr[size - 1];
size--;
if (size == capacity / 4) {
resize(capacity / 2);
}
return item;
}
return -1;
}
void Array::delete_item(int index) {
if (index < size) {
for (size_t i = index; i < size - 1; i++)
{
arr[i] = arr[i + 1];
}
size--;
if (size == capacity / 4) {
resize(capacity / 2);
}
}
}
void Array::remove(int item) {
if (size > 0) {
for (size_t i = 0; i < size; i++)
{
if (arr[i] == item) {
delete_item(i);
}
}
}
}
int Array::find(int item) {
if (size > 0) {
for (size_t i = 0; i < size; i++) {
if (item == arr[i])
return i;
}
}
return -1;
}
void Array::display() {
for (size_t i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
bool Array::binarySearch(int item)
{
int left = 0;
int right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == item)
{
return true;
}
if (arr[mid] < item)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
}
Array::~Array() {
delete[] arr;
}