Permutations

This program displays all possible permutations of n data items.

Programming Issues

The algorithm used is fairly simple. For each item i in a set of n items:

  1. Remove item i from the data set;
  2. Find all permutations of the remaining n - 1 items;
  3. Insert item i back into the set in its original position

The recursive function Perm() shows this algorithm. Each permutation is printed as it is found.

The rest of the code is relatively lengthy, but merely supports the above algorithm by providing it with appropriate data structures. Two data structures are provided:

In order to understand the algorithm used to find the permutations, it is not necessary to delve into the details of these functions or data structures any more than it is necessary to understand exactly how a printf() call produces output on your screen. The main() and Perm() functions describe the algorithm completely. To demonstrate this, two versions of the program are supplied, one using linked lists, and one using arrays. Aside from the files data_####.c and stack_####.c the two versions are identical.

Functions to:

are also provided.

Some performance statistics for this example are available.

Usage

Pass the number of data items to the command line as the single argument. An example session is shown below:

[paul@hermes perm]$ ./perm 3
Permutations of 3 items:

ABC
ACB
BAC
BCA
CAB
CBA

6 permutations in all.

Source and Downloads