Also notice the nested while loop was replaced by a conditional if-else statement, which in-turn reduced the size of the index controller array by one integer. Although performance is relatively unchanged, using a nested while loop instead of a conditional if statement clearly lead to the development of a permutation class as presented in Example_05. This conditional substitution can be made regardless of the counting process utilized. Here's the counting QuickPerm C++ algorithm for your review:
- Initializing all integers in the controller array to zero.
- Increment p[i] by one after the conditional assignment j = p[i]
- While p[i] equals i DO reset p[i] to zero then increment i by one.
A Counting QuickPerm Algorithm - Head Permutations Using a Linear Array without Recursion
// NOTICE: Copyright 2008, Phillip Paul Fuchs
#define N 12
// number of elements to permute. Let N > 2void QuickPerm(void) { unsigned int a[N], p[N]; register unsigned int i, j, tmp;
// Upper Index i; Lower Index jfor(i = 0; i < N; i++) {
// initialize arrays; a[N] can be any typea[i] = i + 1;
// a[i] value is not revealed and can be arbitraryp[i] = 0;
// p[i] == i controls iteration and index boundaries for i}
//display(a, 0, 0); // remove comment to display array a[]i = 1;
// setup first swap points to be 1 and 0 respectively (i & j)while(i < N) { if (p[i] < i) { j = i % 2 * p[i];
// IF i is odd then j = p[i] otherwise j = 0tmp = a[j];
// swap(a[j], a[i])a[j] = a[i]; a[i] = tmp;
//display(a, j, i); // remove comment to display target array a[]p[i]++;
// increase index "weight" for i by onei = 1;
// reset index i to 1 (assumed)} else {
// otherwise p[i] == ip[i] = 0;
// reset p[i] to zeroi++;
// set new index value for i (increase by one)}
// if (p[i] < i)}
// while(i < N)}
// QuickPerm()
QuickPerm - Function to Display Permutations (Optional)
// NOTICE: Copyright 2008, Phillip Paul Fuchs
void display(unsigned int *a, unsigned int j, unsigned int i) { for(unsigned int x = 0; x < N; x++) printf("%d ",a[x]); printf(" swapped(%d, %d)\n", j, i);
//getch(); // Remove comment for "Press any key to continue" prompt.}
// display()
Fundamental Analysis of QuickPerm Above
Number of Objects
to Permute (N)a[N] Display of
Initial Sequencea[N] Display of
Final SequenceTotal Number of Unique
Combinations Produced (N!)3 1 2 3 3 2 1 2 * 3 = 6 4 1 2 3 4 2 3 4 1 6 * 4 = 24 5 1 2 3 4 5 5 2 3 4 1 24 * 5 = 120 6 1 2 3 4 5 6 4 5 2 3 6 1 120 * 6 = 720 7 1 2 3 4 5 6 7 7 2 3 4 5 6 1 720 * 7 = 5040 8 1 2 3 4 5 6 7 8 6 7 2 3 4 5 8 1 5040 * 8 = 40320 9 1 2 3 4 5 6 7 8 9 9 2 3 4 5 6 7 8 1 40320 * 9 = 362880 if N is even 1 2 3 . . . (N - 1) N (N - 2) (N - 1) 2 3 4 . . . N 1 (N - 1)! * N = N! if N is odd 1 2 3 . . . (N - 1) N N 2 3 . . . (N - 1) 1 (N - 1)! * N = N!
A Permutation Ruler:
![]()
Next is tail combinations represented in EXAMPLE 02.