Print k different sorted permutations of a given array in C Program.

Given an array a[] containing N integers, the challenge is to print k different permutations of indices such that the values at those indices form a non-decreasing sequence. Print -1 if it is not possible.

Example

Input: arr[] = {2,5,6,2,2,2,2}, k = 4
Output:
   0 3 4 5 6 1 2
   3 0 4 5 6 1 2
   0 3 4 5 6 1 2
   3 0 4 5 6 1 2

Sort the given array and keep track of the original indices of each element. That gives one required permutation. Now if any 2 continuous elements are equal then they can be swapped to get another permutation. Similarly, the third permutation can be generated.

Algorithm

START
Step 1 -> Declare Function void indice(int n, pair array[])
   Loop For int i=0 and i Declare Function void permutation(int n, int a[], int k)
   Use STL pair arr[n]
   Loop for int i=0 and i In main()
   Declare array a[]={2,5,6,2,2,2,2}
   Declare int n= sizeof(a)/sizeof(a[0])
   Declare int k=4
   Call permutation(n,a,k)
STOP

Example

#include 
using namespace std;
void indice(int n, pair array[]){
   for (int i = 0; i  arr[n];
   for (int i = 0; i 

Output

if we run above program then it will generate following output

0 3 4 5 6 1 2
3 0 4 5 6 1 2
0 3 4 5 6 1 2
3 0 4 5 6 1 2
Updated on: 2019-08-22T06:49:37+05:30

247 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements