I don't understand it at first glance, but I know that the second parameter I of the function represents the first element and the third parameter n represents the last element. So I began to understand it by mathematical induction (I always thought that recursive algorithm should be understood by mathematical induction).
In my opinion, the main points of mathematical induction include the following two points:
1. initial case, that is, the case where n=0 and n= 1;
2. The relationship between k and k- 1, that is, how to find the k-th result when the result of k- 1 is known.
Put it in this question:
1. By considering several situations such as n=0, n= 1, I probably know that the final result of this function is to print a set of full permutations. However, some implementation details have not been fully understood.
2. Given the complete arrangement of k- 1 elements, how to find the complete arrangement of k elements? Combining the recursive call in the perm function is to add 1 to the second parameter, I came up with the answer to this question: first, determine the value of the first element, so that there are less 1 elements that need to be completely arranged, and recursion is established.
Thought of here should be about the same, the idea of the whole algorithm is:
Determine the value of each element in turn starting from element 0. When the value of the last element is determined, print the whole array.
Finally, answer your question:
1.if statement is the processing after determining the value of the last element;
2. The two swap realize the algorithm to determine the first element.
In addition, two exchanges are used here to ensure that the order of each element will not be disturbed after it is completely arranged, otherwise the same element will be exchanged to the first position. I came to this conclusion by mathematical induction again.