I wrote this code to solve a problem in which the user inputs a permutation
of size 'N' and the next permutation of the same elements has to be generated.
I went about this in this way:
given 3 2 5 4 1, starting from the right, the first no. has to be searched which
has a no. greater to it on its right. Here it is 2. Now an array is generated
containing all no.s on its right and greater than it. For 2, it is: 5,4.
Out of these the smallest member is searched for and switched with 2. So, 4 is
switched with 2 to get the Next Permutation: 3 4 5 2 1.
The code I wrote does not show any error but does not return the correct value
when run and gives the same value instead. If I enter '3 2 5 4 1' it returns
the same value as the answer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int N,M,i,n,c,swap,flag,count,small,m;
int Array[100],Key[100];
cout<<"Enter N: ";
cin>>n;
cout<<"\n";
for(n=0;n<100;n++)
{ Array[n]=0; }
//Setting all members of array =0
for(n=0;n<N;n++)
{ cin>>Array[n]; }
//Entering the permutation
M=N;
flag=0;
while(flag<1)
{
M=M1;
i=N;
c=0;
for(n=i;n>M;n=n1)
//Loop which checks the number with greater members on its right
{
if(Array[M]<Array[i])
{
Key[c]=Array[i];
//'Key' is the array containing numbers from Array greater than Array[M] and on its right side
c=c+1;
flag=flag+1;
}
}
}
count=0;
while(count<1)
{
small=0;
for(m=0;m<c;m++)
{
if(Key[m]==small)
{ count=count+1; swap=Key[m]; }
}
small=small+1;
}
//This while loop assigns 'swap' the value of smallest member of 'Key' with which Array[M] has to be switched to produce the next permutation.
for(n=0;n<N;n++)
{if(Array[n]==swap) { m=n; }}
//Array[m] is the member with which Array[M] has to be switched with.
Array[m]=Array[M];
Array[M]=swap;
//Code to swich values.
for(n=0;n<N;n++)
{ cout<<Array[n]<<" "; }
//Printing the Next Permutation.
getch();
}
 