Iterative approach to print all permutations of an Array
Last Updated :
12 Jul, 2025
Given an array arr[] of size N, the task is to generate and print all permutations of the given array. Examples:
Input: arr[] = {1, 2} Output: 1 2 2 1 Input: {0, 1, 2} Output: 0 1 2 1 0 2 0 2 1 2 0 1 1 2 0 2 1 0
Approach: The recursive methods to solve the above problems are discussed here and here. In this post, an iterative method to output all permutations for a given array will be discussed. The iterative method acts as a state machine. When the machine is called, it outputs a permutation and move to the next one. To begin, we need an integer array Indexes to store all the indexes of the input array, and values in array Indexes are initialized to be 0 to n – 1. What we need to do is to permute the Indexes array. During the iteration, we find the smallest index Increase in the Indexes array such that Indexes[Increase] < Indexes[Increase + 1], which is the first "value increase". Then, we have Indexes[0] > Indexes[1] > Indexes[2] > ... > Indexes[Increase], which is a tract of decreasing values from index[0]. The next steps will be:
- Find the index mid such that Indexes[mid] is the greatest with the constraints that 0 ? mid ? Increase and Indexes[mid] < Indexes[Increase + 1]; since array Indexes is reversely sorted from 0 to Increase, this step can use binary search.
- Swap Indexes[Increase + 1] and Indexes[mid].
- Reverse Indexes[0] to Indexes[Increase].
When the values in Indexes become n - 1 to 0, there is no "value increase", and the algorithm terminates. To output the combination, we loop through the index array and the values of the integer array are the indexes of the input array. The following image illustrates the iteration in the algorithm.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <iostream>
using namespace std;
template <typename T>
class AllPermutation {
private:
// The input array for permutation
const T* Arr;
// Length of the input array
const int Length;
// Index array to store indexes of input array
int* Indexes;
// The index of the first "increase"
// in the Index array which is the smallest
// i such that Indexes[i] < Indexes[i + 1]
int Increase;
public:
// Constructor
AllPermutation(T* arr, int length)
: Arr(arr), Length(length)
{
this->Indexes = nullptr;
this->Increase = -1;
}
// Destructor
~AllPermutation()
{
if (this->Indexes != nullptr) {
delete[] this->Indexes;
}
}
// Initialize and output
// the first permutation
void GetFirst()
{
// Allocate memory for Indexes array
this->Indexes = new int[this->Length];
// Initialize the values in Index array
// from 0 to n - 1
for (int i = 0; i < this->Length; ++i) {
this->Indexes[i] = i;
}
// Set the Increase to 0
// since Indexes[0] = 0 < Indexes[1] = 1
this->Increase = 0;
// Output the first permutation
this->Output();
}
// Function that returns true if it is
// possible to generate the next permutation
bool HasNext()
{
// When Increase is in the end of the array,
// it is not possible to have next one
return this->Increase != (this->Length - 1);
}
// Output the next permutation
void GetNext()
{
// Increase is at the very beginning
if (this->Increase == 0) {
// Swap Index[0] and Index[1]
this->Swap(this->Increase, this->Increase + 1);
// Update Increase
this->Increase += 1;
while (this->Increase < this->Length - 1
&& this->Indexes[this->Increase]
> this->Indexes[this->Increase + 1]) {
++this->Increase;
}
}
else {
// Value at Indexes[Increase + 1] is greater than Indexes[0]
// no need for binary search,
// just swap Indexes[Increase + 1] and Indexes[0]
if (this->Indexes[this->Increase + 1] > this->Indexes[0]) {
this->Swap(this->Increase + 1, 0);
}
else {
// Binary search to find the greatest value
// which is less than Indexes[Increase + 1]
int start = 0;
int end = this->Increase;
int mid = (start + end) / 2;
int tVal = this->Indexes[this->Increase + 1];
while (!(this->Indexes[mid] < tVal
&& this->Indexes[mid - 1] > tVal)) {
if (this->Indexes[mid] < tVal) {
end = mid - 1;
}
else {
start = mid + 1;
}
mid = (start + end) / 2;
}
// Swap
this->Swap(this->Increase + 1, mid);
}
// Invert 0 to Increase
for (int i = 0; i <= this->Increase / 2; ++i) {
this->Swap(i, this->Increase - i);
}
// Reset Increase
this->Increase = 0;
}
this->Output();
}
private:
// Function to output the input array
void Output()
{
for (int i = 0; i < this->Length; ++i) {
// Indexes of the input array
// are at the Indexes array
cout << (this->Arr[this->Indexes[i]]) << " ";
}
cout << endl;
}
// Swap two values in the Indexes array
void Swap(int p, int q)
{
int tmp = this->Indexes[p];
this->Indexes[p] = this->Indexes[q];
this->Indexes[q] = tmp;
}
};
// Driver code
int main()
{
int arr[] = { 0, 1, 2 };
AllPermutation<int> perm(arr, sizeof(arr) / sizeof(int));
perm.GetFirst();
while (perm.HasNext()) {
perm.GetNext();
}
return 0;
}
Java
// Java implementation of the approach
class AllPermutation
{
// The input array for permutation
private final int Arr[];
// Index array to store indexes of input array
private int Indexes[];
// The index of the first "increase"
// in the Index array which is the smallest
// i such that Indexes[i] < Indexes[i + 1]
private int Increase;
// Constructor
public AllPermutation(int arr[])
{
this.Arr = arr;
this.Increase = -1;
this.Indexes = new int[this.Arr.length];
}
// Initialize and output
// the first permutation
public void GetFirst()
{
// Allocate memory for Indexes array
this.Indexes = new int[this.Arr.length];
// Initialize the values in Index array
// from 0 to n - 1
for (int i = 0; i < Indexes.length; ++i)
{
this.Indexes[i] = i;
}
// Set the Increase to 0
// since Indexes[0] = 0 < Indexes[1] = 1
this.Increase = 0;
// Output the first permutation
this.Output();
}
// Function that returns true if it is
// possible to generate the next permutation
public boolean HasNext()
{
// When Increase is in the end of the array,
// it is not possible to have next one
return this.Increase != (this.Indexes.length - 1);
}
// Output the next permutation
public void GetNext()
{
// Increase is at the very beginning
if (this.Increase == 0)
{
// Swap Index[0] and Index[1]
this.Swap(this.Increase, this.Increase + 1);
// Update Increase
this.Increase += 1;
while (this.Increase < this.Indexes.length - 1
&& this.Indexes[this.Increase]
> this.Indexes[this.Increase + 1])
{
++this.Increase;
}
}
else
{
// Value at Indexes[Increase + 1] is greater than Indexes[0]
// no need for binary search,
// just swap Indexes[Increase + 1] and Indexes[0]
if (this.Indexes[this.Increase + 1] > this.Indexes[0])
{
this.Swap(this.Increase + 1, 0);
}
else
{
// Binary search to find the greatest value
// which is less than Indexes[Increase + 1]
int start = 0;
int end = this.Increase;
int mid = (start + end) / 2;
int tVal = this.Indexes[this.Increase + 1];
while (!(this.Indexes[mid]<tVal&& this.Indexes[mid - 1]> tVal))
{
if (this.Indexes[mid] < tVal)
{
end = mid - 1;
}
else
{
start = mid + 1;
}
mid = (start + end) / 2;
}
// Swap
this.Swap(this.Increase + 1, mid);
}
// Invert 0 to Increase
for (int i = 0; i <= this.Increase / 2; ++i)
{
this.Swap(i, this.Increase - i);
}
// Reset Increase
this.Increase = 0;
}
this.Output();
}
// Function to output the input array
private void Output()
{
for (int i = 0; i < this.Indexes.length; ++i)
{
// Indexes of the input array
// are at the Indexes array
System.out.print(this.Arr[this.Indexes[i]]);
System.out.print(" ");
}
System.out.println();
}
// Swap two values in the Indexes array
private void Swap(int p, int q)
{
int tmp = this.Indexes[p];
this.Indexes[p] = this.Indexes[q];
this.Indexes[q] = tmp;
}
}
// Driver code
class AppDriver
{
public static void main(String args[])
{
int[] arr = { 0, 1, 2 };
AllPermutation perm = new AllPermutation(arr);
perm.GetFirst();
while (perm.HasNext())
{
perm.GetNext();
}
}
}
// This code is contributed by ghanshyampandey
C#
// C# implementation of the approach
using System;
namespace Permutation {
class AllPermutation<T> {
// The input array for permutation
private readonly T[] Arr;
// Index array to store indexes of input array
private int[] Indexes;
// The index of the first "increase"
// in the Index array which is the smallest
// i such that Indexes[i] < Indexes[i + 1]
private int Increase;
// Constructor
public AllPermutation(T[] arr)
{
this.Arr = arr;
this.Increase = -1;
}
// Initialize and output
// the first permutation
public void GetFirst()
{
// Allocate memory for Indexes array
this.Indexes = new int[this.Arr.Length];
// Initialize the values in Index array
// from 0 to n - 1
for (int i = 0; i < Indexes.Length; ++i) {
this.Indexes[i] = i;
}
// Set the Increase to 0
// since Indexes[0] = 0 < Indexes[1] = 1
this.Increase = 0;
// Output the first permutation
this.Output();
}
// Function that returns true if it is
// possible to generate the next permutation
public bool HasNext()
{
// When Increase is in the end of the array,
// it is not possible to have next one
return this.Increase != (this.Indexes.Length - 1);
}
// Output the next permutation
public void GetNext()
{
// Increase is at the very beginning
if (this.Increase == 0) {
// Swap Index[0] and Index[1]
this.Swap(this.Increase, this.Increase + 1);
// Update Increase
this.Increase += 1;
while (this.Increase < this.Indexes.Length - 1
&& this.Indexes[this.Increase]
> this.Indexes[this.Increase + 1]) {
++this.Increase;
}
}
else {
// Value at Indexes[Increase + 1] is greater than Indexes[0]
// no need for binary search,
// just swap Indexes[Increase + 1] and Indexes[0]
if (this.Indexes[this.Increase + 1] > this.Indexes[0]) {
this.Swap(this.Increase + 1, 0);
}
else {
// Binary search to find the greatest value
// which is less than Indexes[Increase + 1]
int start = 0;
int end = this.Increase;
int mid = (start + end) / 2;
int tVal = this.Indexes[this.Increase + 1];
while (!(this.Indexes[mid]<tVal&& this.Indexes[mid - 1]> tVal)) {
if (this.Indexes[mid] < tVal) {
end = mid - 1;
}
else {
start = mid + 1;
}
mid = (start + end) / 2;
}
// Swap
this.Swap(this.Increase + 1, mid);
}
// Invert 0 to Increase
for (int i = 0; i <= this.Increase / 2; ++i) {
this.Swap(i, this.Increase - i);
}
// Reset Increase
this.Increase = 0;
}
this.Output();
}
// Function to output the input array
private void Output()
{
for (int i = 0; i < this.Indexes.Length; ++i) {
// Indexes of the input array
// are at the Indexes array
Console.Write(this.Arr[this.Indexes[i]]);
Console.Write(" ");
}
Console.WriteLine();
}
// Swap two values in the Indexes array
private void Swap(int p, int q)
{
int tmp = this.Indexes[p];
this.Indexes[p] = this.Indexes[q];
this.Indexes[q] = tmp;
}
}
// Driver code
class AppDriver {
static void Main()
{
int[] arr = { 0, 1, 2 };
AllPermutation<int> perm = new AllPermutation<int>(arr);
perm.GetFirst();
while (perm.HasNext()) {
perm.GetNext();
}
}
}
}
Python3
# Python 3 implementation of the approach
class AllPermutation :
# The input array for permutation
Arr = None
# Index array to store indexes of input array
Indexes = None
# The index of the first "increase"
# in the Index array which is the smallest
# i such that Indexes[i] < Indexes[i + 1]
Increase = 0
# Constructor
def __init__(self, arr) :
self.Arr = arr
self.Increase = -1
self.Indexes = [0] * (len(self.Arr))
# Initialize and output
# the first permutation
def GetFirst(self) :
# Allocate memory for Indexes array
self.Indexes = [0] * (len(self.Arr))
# Initialize the values in Index array
# from 0 to n - 1
i = 0
while (i < len(self.Indexes)) :
self.Indexes[i] = i
i += 1
# Set the Increase to 0
# since Indexes[0] = 0 < Indexes[1] = 1
self.Increase = 0
# Output the first permutation
self.Output()
# Function that returns true if it is
# possible to generate the next permutation
def HasNext(self) :
# When Increase is in the end of the array,
# it is not possible to have next one
return self.Increase != (len(self.Indexes) - 1)
# Output the next permutation
def GetNext(self) :
# Increase is at the very beginning
if (self.Increase == 0) :
# Swap Index[0] and Index[1]
self.Swap(self.Increase, self.Increase + 1)
# Update Increase
self.Increase += 1
while (self.Increase < len(self.Indexes) - 1 and self.Indexes[self.Increase] > self.Indexes[self.Increase + 1]) :
self.Increase += 1
else :
# Value at Indexes[Increase + 1] is greater than Indexes[0]
# no need for binary search,
# just swap Indexes[Increase + 1] and Indexes[0]
if (self.Indexes[self.Increase + 1] > self.Indexes[0]) :
self.Swap(self.Increase + 1, 0)
else :
# Binary search to find the greatest value
# which is less than Indexes[Increase + 1]
start = 0
end = self.Increase
mid = int((start + end) / 2)
tVal = self.Indexes[self.Increase + 1]
while (not (self.Indexes[mid] < tVal and self.Indexes[mid - 1] > tVal)) :
if (self.Indexes[mid] < tVal) :
end = mid - 1
else :
start = mid + 1
mid = int((start + end) / 2)
# Swap
self.Swap(self.Increase + 1, mid)
# Invert 0 to Increase
i = 0
while (i <= int(self.Increase / 2)) :
self.Swap(i, self.Increase - i)
i += 1
# Reset Increase
self.Increase = 0
self.Output()
# Function to output the input array
def Output(self) :
i = 0
while (i < len(self.Indexes)) :
# Indexes of the input array
# are at the Indexes array
print(self.Arr[self.Indexes[i]], end ="")
print(" ", end ="")
i += 1
print()
# Swap two values in the Indexes array
def Swap(self, p, q) :
tmp = self.Indexes[p]
self.Indexes[p] = self.Indexes[q]
self.Indexes[q] = tmp
# Driver code
class AppDriver :
@staticmethod
def main( args) :
arr = [0, 1, 2]
perm = AllPermutation(arr)
perm.GetFirst()
while (perm.HasNext()) :
perm.GetNext()
if __name__=="__main__":
AppDriver.main([])
# This code is contributed by aadityaburujwale.
JavaScript
// JavaScript implementation of the approach
class AllPermutation {
// The input array for permutation
constructor(arr) {
this.Arr = arr;
this.Increase = -1;
this.Indexes = new Array(this.Arr.length);
}
// Initialize and output the first permutation
GetFirst() {
// Allocate memory for Indexes array
this.Indexes = new Array(this.Arr.length);
// Initialize the values in Index array from 0 to n - 1
for (let i = 0; i < this.Indexes.length; i++) {
this.Indexes[i] = i;
}
// Set the Increase to 0
// since Indexes[0] = 0 < Indexes[1] = 1
this.Increase = 0;
// Output the first permutation
this.Output();
}
// Function that returns true if it is possible to generate the next permutation
HasNext() {
// When Increase is in the end of the array, it is not possible to have next one
return this.Increase !== this.Indexes.length - 1;
}
// Output the next permutation
GetNext() {
// Increase is at the very beginning
if (this.Increase === 0) {
// Swap Index[0] and Index[1]
this.Swap(this.Increase, this.Increase + 1);
// Update Increase
this.Increase++;
while (
this.Increase < this.Indexes.length - 1 &&
this.Indexes[this.Increase] > this.Indexes[this.Increase + 1]
) {
this.Increase++;
}
} else {
// Value at Indexes[Increase + 1] is greater than Indexes[0]
// no need for binary search, just swap Indexes[Increase + 1] and Indexes[0]
if (this.Indexes[this.Increase + 1] > this.Indexes[0]) {
this.Swap(this.Increase + 1, 0);
} else {
// Binary search to find the greatest value which is less than Indexes[Increase + 1]
let start = 0;
let end = this.Increase;
let mid = Math.floor((start + end) / 2);
let tVal = this.Indexes[this.Increase + 1];
while (!(this.Indexes[mid] < tVal && this.Indexes[mid - 1] > tVal)) {
if (this.Indexes[mid] < tVal) {
end = mid - 1;
} else {
start = mid + 1;
}
mid = Math.floor((start + end) / 2);
}
// Swap
this.Swap(this.Increase + 1, mid);
}
// Invert 0 to Increase
for (let i = 0; i <= this.Increase / 2; i++) {
this.Swap(i, this.Increase - i);
}
// Reset Increase
this.Increase = 0;
}
this.Output();
}
Output() {
let temp = "";
for (var i = 0; i < this.Indexes.length; i++) {
temp += this.Indexes[i]+" ";
//console.log(this.Arr[this.Indexes[i]] + " ");
}
console.log(temp);
}
Swap(p, q) {
var tmp = this.Indexes[p];
this.Indexes[p] = this.Indexes[q];
this.Indexes[q] = tmp;
}
}
let arr = [0, 1, 2];
let perm = new AllPermutation(arr);
perm.GetFirst();
while (perm.HasNext()) {
perm.GetNext();
}
// This code is contributed by abn95knd1.
Output:0 1 2
1 0 2
0 2 1
2 0 1
1 2 0
2 1 0
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem