I have the following code which finds the max value and shifts the values left:
@Override
public void remove() throws QueueUnderflowException {
int max = 0;
int index = 0;
if (isEmpty()) {
throw new QueueUnderflowException();
} else {
for (int i = 0; i < tailIndex + 1; i++) {
int current = ((PriorityItem<T>) storage[i]).getPriority();
if (current > max) {
max = current;
index = i;
}
}
for (int i = 0; i < tailIndex + 1; i++) {
int current = ((PriorityItem<T>) storage[i]).getPriority();
if (current >= max) {
storage[i] = storage[i + 1];
}
}
tailIndex = tailIndex - 1;
}
}
However, the elements are shifted only once because of my if statement which does it during the time the value is max, how would I shift the remaining values without any duplication.
here is the input :
[(y, 1), (o, 8), (u, 7), (o, 0)]
The desired output:
(y, 1), (u, 7), (o, 0)]
The current output:
[(y, 1), (u, 7), (u, 7)]
Your second loop has to be simplified in the following way? Your if check is not correct in the second loop, you should check whether you should shift or not, not anymore check against the priority value, but only on the index
for (int i = 0; i < tailIndex + 1; i++) {
if (i >= index) {
storage[i] = storage[i + 1];
}
}
Or even simpler
for (int i = index; i < tailIndex + 1; i++) {
storage[i] = storage[i + 1];
}