-
Notifications
You must be signed in to change notification settings - Fork 0
/
double and half array.cpp
136 lines (120 loc) · 2.29 KB
/
double and half 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
#include <iostream>
using namespace std;
class Array
{
private:
int capacity;
int lastIndex = -1;
int *ptr;
public:
Array(int);
void getArray();
void append(int);
void inserElement(int, int);
void deleteElement(int);
void count();
int capacity();
bool isEmpty();
void halfarray()
{
int *newptr = new int[capacity / 2];
for (int i = 0; i <= lastIndex; i++)
{
newptr[i] = ptr[i];
}
delete[] ptr;
ptr = newptr;
capacity = capacity / 2;
}
void doubleArray()
{
int *newptr = new int[capacity];
for (int i = 0; i <= lastIndex; i++)
{
newptr[i] = ptr[i];
}
delete[] ptr;
ptr = newptr;
capacity *= 2;
}
};
bool Array::isEmpty()
{
return lastIndex == -1;
}
int Array::capacity()
{
return capacity;
}
void Array::deleteElement(int index)
{
if (index > lastIndex || index < 0)
{
cout << "invalid index";
}
else
{
if (capacity/2 >= lastIndex+1 && capacity>1)
halfarray();
for (int i = index; i < lastIndex; i++)
{
ptr[i] = ptr[i + 1];
}
lastIndex = -1;
}
}
void Array::count()
{
cout << lastIndex + 1 << endl;
}
void Array::inserElement(int element, int index)
{
if (index < 0 || index > lastIndex + 1)
cout << "Invalid Index" << endl;
else
{
if (lastIndex == capacity - 1)
doubleArray();
for (int i = lastIndex; i >= index; i--)
ptr[i] = ptr[i - 1];
ptr[index] = element;
lastIndex++;
}
}
void Array::append(int value)
{
if (lastIndex == capacity - 1)
doubleArray();
lastIndex++;
ptr[lastIndex] = value;
}
Array::Array(int size)
{
ptr = new int[size];
capacity = size;
}
void Array::getArray()
{
for (int i = 0; i < capacity; i++)
{
cout << ptr[i] << " ";
}
}
int main()
{
Array obj(5);
obj.append(2);
obj.append(3);
obj.append(4);
obj.append(5);
obj.append(2);
// obj.append(3);
// obj.append(4);
// obj.append(5);
// obj.append(6);
// obj.append(6);
// obj.deleteElement(0);
// obj.deleteElement(1);
obj.getArray();
return 0;
}