Lecture
13: Implementing
a Queue with an array or ArrayList
Announcements:
Exams are graded; average score = 80.4 – good
result!
H4 is graded – your grade is in your handin directory
P3 is posted, due Mar 15 – read & bring
questions on Thursday
H5 will be posted on Thursday, due on March 15
first try:
complexity of enqueue
& dequeue:
front |
enqueue(ob) |
time |
dequeue() |
time |
first item |
add(ob) |
O(1) |
remove(0) |
O(N) |
last item |
Add(0,ob) |
O(N) |
Remove(size()-1) |
O(1) |
second try:
·
keep
frontIndex, rearIndex &
let front of queue move
·
enqueue: //basic
code
rearIndex++;
items[rearIndex] = ob;
numItems++;
·
dequeue: //basic code
numItems - -;
frontIndex++
return items[frontIndex-1];
both operations are O(1) - that's good!
need to take care of when rearIndex = items.length-1
·
could
just expand array, but that wastes a lot of space
·
instead: let rear
of queue wrap around & reuse items[0]…
wrap around & reuse
items[0]
o
circular
list within the array
o
still
might need to expand the array, but use all of it
You try:
write the code for enqueue, assuming
array still has space
then add call
to expandCircularArray if out of space
public void
enqueue(Object ob) {
if (numItems
== items.length)
expandCircularArray;
if (rearIndex == items.length -1)
rearIndex
= 0;
else
rearIndex++;
items[rearIndex] = ob;
numItems++;
}
You try:
write steps for expandCircularArray() in English
if you have extra
time, write the code
Solution:
Steps:
1.
Allocate
new array, tmp, twice the size
2.
copy values in items[frontIndex]
.. items[rearIndex] into tmp[0] … tmp[numItems-1]
3.
set
items = tmp
4.
set
frontIndex =
0, rearIndex = numItems-1;
for (k = 0; k < numItems; k++)
{
items[k] = items[frontIndex];
frontIndex
++;
if (frontIndex = items.length)
frontIndex
= 0;
}
Compare: Queue implemented via an array vs LinkedList
space:
o
linked
list stores pointer + data
o
but
the array can be ½ empty
time:
o
linked
list all O(1)
o
array
also all O(1)
ease of implementation:
o
linked
list is easier if have LinkedList class
o
otherwise,
both implementations are similar