[net.micro.pc] Permutations

vifl@hou2f.UUCP (M.MEKETON) (07/23/84)

Here is an implementation of the permutation algorithm in C, without
using recursion.  It takes an integer, n, on the command line and creates
all the permutations of {1,2,..,n}.  Translations to PASCAL, FORTRAN, etc.,
are straigtforward.

#define MAX_N 10
main(argc,argv)
int argc;
char *argv[];
{
 int N, x[MAX_N+2], i, j, y[MAX_N+1];

 sscanf(argv[1],"%d",&N);

 for (i=1;i<=N;x[i++]=1);
 while (x[N+1] < 1)
       {
	for (i=1;i<=N;y[i++]=i);
	for (i=N;i>=2;i--)
	       {
		printf("%d ",y[x[i]]);
		for (j=x[i];j<N;j++) y[j] =y[j+1];
	       }
	printf("%d\n",y[1]);
	i=1;
	x[1]++;
	while (x[i] > i) {x[i] = 1; x[++i]++;}
       }
}

Marc S. Meketon
ATT-BL
Holmdel, NJ