Artificial intelligent assistant

How to systematically (ie: algorithmically) generate permutations of a set? Given the first $n$ natural numbers, how do you systematically generate all of the $n!$ permutations of that set? I can do it for a known $n$ using a computer program, but it requires $n$ nested loops. I'm sure there must be a more efficient way.

If $S_n$ is the set of all permutations of $\\{1,\dotsc,n\\}$ then a recursive formulation is

$$ S_{n+1} = \bigcup_{i=0}^n\ \\{ f_i(s) \mid s \in S_n \\}$$

where $f_i(s)$ denotes the permutation obtained by inserting $n+1$ after the $i$-th entry of the $n$-permutation $s$. (For $i=0$ this is inserting in the first place.)

You can write this as a tail-recursive algorithm if you define a helper function, but maybe the details of that are a better fit on e.g. StackOverflow.

xcX3v84RxoQ-4GxG32940ukFUIEgYdPy 0c0c94d4282f4c4b886a472c00ccbd42