Take the example of generating the permutations of the array ['a', 'b', 'c', 'd'].
Assume that the function named generate(n, arr) with two parameters: n is the length of the array; and the arr is the array to be dealt with.
And the calling statement would be: generate(4, ['a', 'b', 'c', 'd']);.
There's a for loop inside the algorithm. So:
generate(4, ['a', 'b', 'c', 'd']);
-
for: i = 0
-
generate(3, ['a', 'b', 'c', 'd']);-
for: i = 0
-
generate(2, ['a', 'b', 'c', 'd']);-
for: i = 0
-
generate(1, ['a', 'b', 'c', 'd'])console.log(arr)would be["a", "b", "c", "d"];return;
-
swap
arr(i)andarr[n - 1], the array swapped to be['b', 'a', 'c', 'd']
-
-
for: i = 1
-
generate(1, ['b', 'a', 'c', 'd']);console.log(arr)would be["b", "a", "c", "d"];return;
-
swap
arr(i)andarr[n - 1], the array swapped to be['b', 'a', 'c', 'd'],with no changes made actually.
-
-
-
swap
arr(0)andarr[n - 1],the array be['c', 'a', 'b', 'd']
-
-
for: i = 1
generate(2, ['c', 'a', 'b', 'd']);- swap
-
for: i = 2
generate(2, array);- swap
-
-
swap
-
-
for: i = 1
generate(3, array);- swap
-
for: i = 2
generate(3, array);- swap
-
for: i = 3
generate(3, array);- swap
Also a much more better picture can be found here.
Thank you for this, it helped me understand the algorithm.