A permutation is an ordering of the elements. To generate all n! of them, fix position k by swapping each candidate into it, recurse on the rest, then swap back to restore the array. When k reaches the last index, one complete permutation is ready.
Remember
permute(k):
if k == n - 1: print a; return
for i in k..n-1:
swap(a[k], a[i])
permute(k + 1)
swap(a[k], a[i]) /* backtrack */
Reference
Cheat Sheet
Keep these facts handy while you work with Generating Permutations in C in C.
Topic
Detail
Count
n!
Technique
Swap, recurse, swap back
Time
O(n x n!)
Order
Not lexicographic
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Maze Solving in C.
Example 1 — Permutations of 1, 2, 3
Six results.
C
#include <stdio.h>
static int total;
static void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }
static void permute(int a[], int n, int k) {
if (k == n - 1) {
total++;
for (int i = 0; i < n; i++) printf("%d%s", a[i], i + 1 < n ? " " : "");
printf("\n");
return;
}
for (int i = k; i < n; i++) {
swap(&a[k], &a[i]);
permute(a, n, k + 1);
swap(&a[k], &a[i]);
}
}
int main(void) {
int a[] = {1, 2, 3};
permute(a, 3, 0);
printf("total: %d\n", total);
return 0;
}
Output
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
3 1 2
total: 6
How It Works
With 1 fixed first, the rest produce 1 2 3 and 1 3 2.
Swapping 2 into position 0 gives 2 1 3 and 2 3 1.
Swapping 3 into position 0 gives 3 2 1 and 3 1 2.
Edge Cases & Pitfalls
Check these before relying on Generating Permutations in C in real programs.
restore
Missing swap back
Without restoring the array, later iterations see a scrambled array and miss permutations.
explode
Factorial growth
10 elements already have 3,628,800 permutations.
Remember
Key Takeaways
n! results.
Swap, recurse, swap back.
Backtracking in its simplest form.
One line: A permutation is an ordering of the elements.
Frequently Asked Questions
n! (n factorial).
To restore the array so the next candidate for this position starts from the original arrangement.
Continue with "Maze Solving in C" next. Search a grid maze with depth-first backtracking and print the path. The C Recursion and Backtracking hub lists every topic in order.