Sorting Using Networks of Queues and Stacks

Inspired by Knuth [2, p. 234], we wish to consider the following problem: Suppose we are presented with the layout of a railroad switchyard (Figure 1 ). I f a train is driven into one end of the yard, what rearrangements of the cars may be made before the train comes out the other end? In order to get a handle on the problem, we must introduce some formalization. A switchyard is an acyclic directed graph, with a unique source and a unique sink (Figure 2). Each vertex represents a siding. The vertex/siding is assumed to have indefinite storage space and may be a stack, a queue, or a deque of some sort (see Knuth [2, p. 234]). A stack is a siding which has the property tha t the last element inserted is the first to be removed. A queue has the proper ty tha t the first element inserted is the first to be removed. In the switchyard, the sidings associated with the source and sink are assumed to be queues. Suppose a finite sequence of numbers s = (sl, s2, • • • , sn) is placed in the source queue of a switchyard (Figure 3). We may rearrange s by moving the elements of s through the switchyard. At each step, an element is moved from some siding to another siding along an arc of the switchyard. After a suitable number of such moves, all elements will be in the sink queue. I f they are in order, smallest to largest, we have sorted the sequence s using the switchyard. We wish to analyze the sequences s which may be sorted in a switchyard Y. We lose nothing in our formalism by allowing storage only on the vertices, and not on the arcs of the switchyard. We ignore questions concerning the finite size of the sidings; assuming small sidings complicates the problem considerably. A circuit in the switchyard will allow us to sort any sequence; thus we do not allow circuits. Having established our model, we proceed to discover its properties.