Next permutation C code
If all permutations of the array are sorted in lexicographical order then next permutation of that string is the permutation that follows it in the sorted order.
For example
find next permutation of 123
Solution
Find all permutation of string
={123,132,231,213,321,312}
sort all permutation of string in lexicographical order
{123,132,213,231,312,321}
so next permutation of 123 is 132.
Next permutation C code
#include<stdio.h>
#include<string.h>
void reverse(char s[],int start,int end);
void nextpermutation(char s[]);
void main()
{
char s[10];
printf("enter string");
scanf("%s",s);
nextpermutation(s);
printf("%s",s);
}
void nextpermutation(char s[])
{
int n=strlen(s);
int k=n-2;
int i;
if(strlen(s)==0||s==NULL)
return;
for(i=n-1;i>0;i--)
{
if(s[i]<s[i-1])
k--;
else
break;
}
if(k==-1)
{
reverse(s,0,n-1);
return;
}
for(i=n-1;i>0;i--)
{
if(s[i]>s[k])
{
int temp;
temp=s[k];
s[k]=s[i];
s[i]=temp;
break;
}
}
reverse(s,k+1,n-1);
}
void reverse(char s[],int start,int end)
{
int temp;
while(start<end)
{
temp=s[start];
s[start]=s[end];
s[end]=temp;
start++;
end--;
}
}
Output
enter string123
132
0 Comments