Fixed Bug with FIFOQueue performance

This commit is contained in:
Speiger 2021-12-26 00:08:19 +01:00
parent ead34009c6
commit dbfae33074
2 changed files with 22 additions and 3 deletions

View File

@ -82,7 +82,7 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K
*/ */
public ARRAY_FIFO_QUEUE(int capacity) { public ARRAY_FIFO_QUEUE(int capacity) {
if (capacity < 0) throw new IllegalArgumentException("Initial capacity (" + capacity + ") is negative"); if (capacity < 0) throw new IllegalArgumentException("Initial capacity (" + capacity + ") is negative");
array = NEW_KEY_ARRAY(Math.max(MIN_CAPACITY, capacity)); array = NEW_KEY_ARRAY(Math.max(MIN_CAPACITY, capacity+1));
minCapacity = array.length; minCapacity = array.length;
} }
@ -133,7 +133,7 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K
#if TYPE_OBJECT #if TYPE_OBJECT
array[first] = null; array[first] = null;
#endif #endif
first = ++first % array.length; if(++first == array.length) first = 0;
reduce(); reduce();
return data; return data;
} }
@ -153,7 +153,8 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K
@Override @Override
public KEY_TYPE peek(int index) { public KEY_TYPE peek(int index) {
if(first == last || index < 0 || index > size()) throw new NoSuchElementException(); if(first == last || index < 0 || index > size()) throw new NoSuchElementException();
return array[(first + index) % array.length]; index += first;
return index > array.length ? array[index-array.length] : array[index];
} }
@Override @Override

View File

@ -82,6 +82,24 @@ public abstract class BaseIntPriorityQueueTest extends BaseIntIterableTest
} }
} }
@Test
public void testUnorderedPeek() {
EnumSet<PriorityQueueTest> valid = getValidPriorityQueueTests();
if(valid.contains(PriorityQueueTest.IN_OUT) && valid.contains(PriorityQueueTest.PEEK) && !isUnsortedRead()) {
IntPriorityQueue queue = create(EMPTY_ARRAY);
for(int i = 0;i<100;i++) {
queue.enqueue(i);
}
for(int i = 0;i<25;i++) {
queue.dequeue();
queue.enqueue(i);
}
for(int i = 0;i<100;i++) {
Assert.assertEquals((i+25) % 100, queue.peek(i));
}
}
}
@Test @Test
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void testToArray() { public void testToArray() {