Programming Problems Using Recursion 239
2
5
The next number is 3 so 2 is popped from the stack and 3 is pushed.
3
5
The next number is 5 so 3 is popped and 5 is pushed.
5
5
The last number 4 is pushed.
4
5
5
Finally, all numbers are popped and the output sequence is 1, 2, 3, 4, 5, 5. It is sorted.
Thus, <1, 5, 2, 3, 5, 4> is stack sortable.
If the same largest value M (5 in this example) appears multiple times, which M should
be chosen for breaking the sequence into A, M , and B? Should it be the first M , the second
M, the last one, or will any one do? The answer is the first M because we compare only the
smallest element in B and do not care about the largest element in B. If we choose an M
other than the first, then the first M is in A and the sequence would never be considered
stack sortable, which is a mistake.
After breaking the sequence into the three parts, the same procedure is applied recur-
sively to A and B to determine whether in turn they are stack sortable. The algorithm for
checking stack sortable is described as follows:
1. An empty sequence is stack sortable. This is a base case.
2. Find the largest value in the sequence. If this value appears multiple times in the
array, select the first one.
3. Divide the sequence into three parts.
4. If both A and B are empty, then the sequence is stack sortable. The sequence has
only one element. This is another base case.
5. If A is empty (B must not be empty), then jump to step 9.
6. If B is empty (A must not be empty), then jump to step 8.
7. Since neither A nor B is empty, find M
A
and m
B
. If M
A
> m
B
, then the sequence is
not stack sortable. This is another base case.
8. Recursively check whether A is stack sortable.
9. Recursively check whether B is stack sortable.
The following implementation checks whether a sequence is stack sortable. We have used
the permutation program to generate all possible test cases.
// stac ksort . c1
#in clude < stdio .h >2
#in clude < stdlib .h >3
#in clude < string .h >4
int findIndex ( i n t * arr , i nt first , in t last , int maxmin )5
// find the index of the largest or s m allest element6
// the range is expressed by the i n d exe s [ first , last ]7
// maxmin = 1: find largest , maxmin = 0: find smallest8