236 Intermediate C Programming
}62
combine ( arr , num , sel );63
free ( arr );64
return EXIT _SUCCES S ;65
}66
When sum equals sel, enough items have been selected and the selected items are
printed. When ind equals num, no more items are available for selection. Line 30 selects the
item and one is added to sum when recursively calling combineHelp. Line 33 “unselects” the
item and sum is unchanged in the recursive call. Either the item is selected or it is not. The
helper function recursively calls itself to determine whether to select the remaining items.
From the examples of permutations and combinations, you can see recursion is a natural
way of solving these problems. Recursion is a good approach when the solutions
have “branches”. In permutation, each element can be in one of many locations. After
setting one element to a particular location, the next element also can be in one of many
locations. By putting recursive calls inside a loop, the solution naturally solves permutations.
For combinations, each element may be selected or not and there are two branches. One
reason that makes recursion a better solution is that the number of iterations changes. For
both cases, the call stack keeps the values of the array indexes. The indexes indicate which
element to consider next. Without using recursion, programmers have to allocate memory
for keeping the values of the indexes.
15.4 Stack Sort
A stack can be used to sort a sequence of numbers, if the sequence satisfies some con-
ditions. What is a “stack”? A stack can store information based on the “first-in, last-out”
rule. The call stack is a stack that is used to control the flow of execution of a computer
program. Not every stack is a call stack. The “stack” in this section is unrelated to the call
stack described earlier. The stack sort algorithm is described as follows:
1. Create an empty stack.
2. Read one number from the sequence, call it x.
3. If the stack is empty, push the number x to the stack.
4. When the stack is not empty, we call the number at the top of the stack y.
5. If y <= x, pop y from the stack. Continue steps 4 and 5 until either the stack is empty
or top of the stack is greater x.
6. If y > x, then push x to the stack.
7. Repeat steps 2 to 6 until finishing the input sequence.
8. If the stack is not empty, then pop all remaining numbers from the stack.
9. The sequence of numbers popped from the stack is sorted if the input sequence is
“stack-sortable”. The definition is described further below.
Stack sort is a theoretically interesting algorithm, because it is fast—faster than quick
sort—but works only under particular circumstances. Those circumstances will be explained,
but first a few examples to illustrate how stack sort works.
15.4.1 Example 1
Consider the sequence <2, 1>. When 2 is read from the sequence, the stack is empty
and 2 is pushed on to the stack (step 3). Next, 1 is read from the sequence, 1 is smaller