-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamicarray.cpp
107 lines (92 loc) · 1.38 KB
/
dynamicarray.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
#include <iostream>
#include <cstdlib>
class darray{ int *array; int *temp; int length; int capacity; public: darray
(){ length = 0; capacity = 1; array = new int[capacity]; temp = new int
[capacity]; }
void insertatend(int n)
{
length++;
if(length > capacity)
{
resize();
}
array[length-1] = n;
}
void insertanywhere(int pos, int n)
{
if(length = capacity)
{
resize();
}
for(int i = length-1; i>pos; i--)
{
array[i] = array[i-1];
}
array[pos] = n;
length++;
}
void deleteatend(int n)
{
if(length == 0)
{
std::cout<<"The array is empty!"<<std::endl;
exit(1);
}
length--;
array[length-1] = n;
while(length == capacity/2)
{
shrink();
}
}
void resize()
{
capacity *= 2;
temp = array;
array = new int[capacity];
copy();
}
void shrink()
{
capacity /= 2;
temp = array;
array = new int[capacity];
copyshrinked();
}
void copyshrinked()
{
for(int i=0; i<length; i++)
{
array[i] = temp[i];
}
temp = new int[capacity];
}
void copy()
{
for(int i=0; i<length; i++)
{
array[i] = temp[i];
}
temp = new int[capacity];
}
void show()
{
if(length == 0)
{
std::cout<<"Empty array"<<std::endl;
exit(0);
}
for(int i=0; i<length; i++)
{
std::cout<<array[i]<<std::endl;
}
}
};
int main()
{
darray a;
a.insertatend(5);
a.deleteatend(5);
a.show();
return 0;
}