Worksheet 20: Dynamic Array Deque and Queue
In Preparation: Read Chapter 7 to learn more about the Queue and Deque data types. If
you have not done it already, complete lessons 14 and 16 to learn more about the basic
features of the dynamic array data type.
A question in the worksheet on the dynamic array stack asked why you cannot use a
Dynamic Array as the basis for an efficient queue. This is because adding to or removing
from the first location (that is, index position 0) is very slow O(n).
Removing a value requires elements to slide left.
Sliding left means every element must be
moved, and hence is an O(n) operation.
Adding a value requires elements to slide right.
Sliding right opens up the location where a
new value can be inserted. Once more,
however, every element must be moved, and
hence this is an O(n) operation.
This does not mean that a Dynamic Array-like data structure cannot be used to implement
a queue. The key insight is that we can allow the starting location of the block of
elements to “float”, rather than being fixed at location zero. An internal integer data field
records the current starting location.
Notice that the “logical” index no longer corresponds to the physical index. The value
with logical index zero is found in this diagram at array location 2. The value with logical
index 1 is found at location 3, and so on.
With this change, it is now easy to implement additions or removal from either front or
back. To add to the front, simply decrement the starting location, and place the new
element in the new starting place. To add to the back, simply increase the size, and place
the new value in the location determined by the addition of the starting location and size.
But there is one subtle complexity. The block of values stored in the collection can wrap
around from the end back to the beginning: