algorithm for possible sequence of array elements

Consider I have an array with 3 elements.


4 6 7

I want to know that is there any algorithm to find all possible rearranging for that array like,


4 6 7
4 7 6
6 4 7
6 7 4
7 4 6
7 6 4

Is there any algorithm for that or any ways for solving it.

http://www.cplusplus.com/reference/algorithm/next_permutation/

1 Like

Yes there is.

You can write your own function to calculate all permutations or use built-in next_permutation function.

For example writing your own:

#include<bits/stdc++.h>
using namespace std;

int arr[3]={1,2,3};


void gen(int l, int r)
{
	if(l==r)
	{
		cout << arr[0] << " - " << arr[1] << " - " << arr[2] << "\n";
	}else {
		for(int i=l;i<=r;++i)
		{
			swap(*(arr+l), *(arr+i));
			gen(l+1,r);
			swap(*(arr+l), *(arr+i));
		}
	}
}

int main()
{
	int n=3;
	gen(0,n-1);
}

Or using built-in:

    do
	{
		cout << arr[0] << " - " << arr[1] << " - " << arr[2] << "\n";
	}while(next_permutation(arr,arr+3));

Links:

1 Like