Permutations without recursive function call
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Permutations are a fundamental concept in combinatorics and are used to solve many computational problems. A permutation of a set is a rearrangement of its elements into a sequence or linear order. The mathematical notation for the number of permutations of a set with elements is (n factorial), which is computed as .
In computer science, generating permutations can be accomplished through various methods. While recursive approaches are common and can be effective for generating permutations, they may not always be suitable due to call stack limitations in large datasets or the need for iterative processing. This article will explore how to generate permutations without using recursive function calls, providing a more iterative and sometimes efficient method.
Iterative Approach for Permutations
To generate permutations iteratively, one can employ several algorithms. One popular approach is to use the Steinhaus-Johnson-Trotter algorithm, also known as the plain changes or the permutation algorithm. This method generates permutations in lexicographical order and makes use of data structures such as arrays and loops.
Algorithm Explanation
The Steinhaus-Johnson-Trotter algorithm generates permutations by successively swapping adjacent elements. A "direction" is associated with each element to indicate the swap direction, and these directions are reversed when certain conditions are met, thus producing the next permutation order.
Here is a step-by-step explanation of the algorithm:
- Initial Setup:
- Begin with a list of numbers sorted in ascending order.
- Assign a "direction" to each element, initially pointing to the left.
- Generate Permutations:
- Identify the largest mobile integer. A mobile integer is an element that can be swapped in the direction it’s currently pointing.
- Swap the identified mobile integer with the adjacent element in its direction.
- Reverse the direction of any integers larger than the mobile integer after the swap.
- Repeat:
- Continue the process until no mobile integers remain, indicating that all permutations have been generated.
Example Code
Below is a Python implementation of the iterative approach based on the Steinhaus-Johnson-Trotter algorithm:

