-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynArray.java
More file actions
135 lines (122 loc) · 2.18 KB
/
Copy pathDynArray.java
File metadata and controls
135 lines (122 loc) · 2.18 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
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
package program05;
public class DynArray
{
private double[] array;
private int size;
private int nextIndex;
public DynArray()
{
array = new double[1];
size = 1;
nextIndex = 0;
}
public int arraySize()
{
return size;
}
public int elements()
{
return nextIndex;
}
public double at(int index)
{
if (0 <= index && index < nextIndex)
return array[index];
else
return Double.NaN;
}
private void grow()
{
double arrayNew[];
size = size * 2;
arrayNew = new double[size];
for (int i = 0; i < array.length; i++)
{
double temp;
temp = array[i];
arrayNew[i] = temp;
}
array = arrayNew;
}
private void shrink()
{
double arrayNew[];
size = array.length / 2;
arrayNew = new double[size];
for (int i = 0; i < size; i++)
{
double temp;
temp = array[i];
arrayNew[i] = temp;
}
array = arrayNew;
}
public void insertAt(int index, double value)
{
if (index >= 0 && index <= nextIndex)
{
double temp1;
for (int i = index; i <= nextIndex; ++i)
{
if (nextIndex == array.length)
{
grow();
}
temp1 = array[i];
array[i] = value;
value = temp1;
}
}
nextIndex = nextIndex + 1;
}
public void insert(double value)
{
if (nextIndex == array.length)
{
grow();
}
array[nextIndex] = value;
nextIndex = nextIndex + 1;
}
public double removeAt(int index)
{
if (index >= 0 && index < nextIndex)
{
double temp1;
double temp2 = 0;
double value = array[index];
for (int i = nextIndex - 1; i >= index; --i)
{
temp1 = array[i];
array[i] = temp2;
temp2 = temp1;
}
nextIndex = nextIndex - 1;
return value;
} else
return Double.NaN;
}
public double remove()
{
double value1;
if (nextIndex == 0)
return Double.NaN;
else
{
if (nextIndex == array.length / 2)
{
shrink();
}
value1 = array[nextIndex - 1];
nextIndex = nextIndex - 1;
}
return value1;
}
public void printArray()
{
for (int i = 0; i < nextIndex; ++i)
{
System.out.println("array.at(" + i + ") = " + array[i] + " ");
}
}
}