Skip to content

Commit ee89646

Browse files
author
phishman3579
committed
Updated the ArrayQueue to get removing from the middle working correctly now that I use a wrap around array implementation
git-svn-id: https://java-algorithms-implementation.googlecode.com/svn/trunk@413 032fbc0f-8cab-eb90-e552-f08422b9a96a
1 parent c30ab44 commit ee89646

File tree

1 file changed

+15
-8
lines changed
  • src/com/jwetherell/algorithms/data_structures

1 file changed

+15
-8
lines changed

src/com/jwetherell/algorithms/data_structures/Queue.java

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ public T poll() {
6060
}
6161

6262
int shrinkSize = (size + (size<<1));
63-
if (size >= MINIMUM_SIZE && (array.length > shrinkSize)) {
63+
if (shrinkSize >= MINIMUM_SIZE && (array.length > shrinkSize)) {
6464
array = Arrays.copyOfRange(array, firstIndex, lastIndex);
6565
lastIndex = size;
6666
firstIndex = 0;
@@ -90,18 +90,25 @@ public boolean remove(T value) {
9090
}
9191

9292
private boolean remove(int index) {
93-
int size = size();
94-
if (index<0 || index >=size) return false;
93+
if (index<0 || index >= array.length) return false;
94+
if (index==firstIndex) return (poll()!=null);
9595

96-
int adjIndex = firstIndex+index;
97-
if (adjIndex != --size) {
96+
int adjIndex = index%array.length;
97+
int adjLastIndex = (lastIndex-1)%array.length;
98+
if (adjIndex != adjLastIndex) {
9899
// Shift the array down one spot
99-
System.arraycopy(array, adjIndex + 1, array, adjIndex, (array.length - (adjIndex+1)));
100+
System.arraycopy(array, index+1, array, index, (array.length - (index+1)));
101+
if (adjLastIndex<firstIndex) {
102+
//Wrapped around array
103+
array[array.length-1] = array[0];
104+
System.arraycopy(array, 1, array, 0, firstIndex-1);
105+
}
100106
}
101-
array[size] = null;
107+
array[adjLastIndex] = null;
102108

109+
int size = size();
103110
int shrinkSize = (size + (size<<1));
104-
if (size >= MINIMUM_SIZE && (array.length > shrinkSize)) {
111+
if (shrinkSize >= MINIMUM_SIZE && (array.length > shrinkSize)) {
105112
System.arraycopy(array, 0, array, 0, shrinkSize);
106113
}
107114

0 commit comments

Comments
 (0)