SKEDSOFT

Design Analysis Of Algorithm
Figure 10.2: A queue implemented using an array Q[1 12]. Queue elements appear only in the lightly shaded positions. (a) The queue has 5 elements, in locations Q[7 11]. (b) The configuration of the queue after the calls ENQUEUE(Q, 17), ENQUEUE(Q, 3), and ENQUEUE(Q, 5). (c) The configuration of the queue after the call DEQUEUE(Q) returns the key value 15 formerly at the head of the queue. The new head has key 6.

In our procedures ENQUEUE and DEQUEUE, the error checking for underflow and overflow has been omitted. (Exercise 10.1-4 asks you to supply code that checks for these two error conditions.)

	ENQUEUE(Q, x)
1  Q[tail[Q]]  x
2  if tail[Q] = length[Q]
3     then tail[Q]  1
4     else tail[Q]  tail[Q]   1

DEQUEUE(Q)
1  x  Q[head[Q]]
2  if head[Q] = length[Q]
3     then head[Q]  1
4     else head[Q]  head[Q]   1
5  return x

Figure 10.2 shows the effects of the ENQUEUE and DEQUEUE operations. Each operation takes O(1) time.