Generating permutation of characters

Problem statement
Write a c program to print all the permutation of given set of number
#include<stdio.h>
#include<stdlib.h>
void swap (char *x, char *y)        /* Function to swap values at two pointers */
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
  
/* Function to print permutations of string
   This function takes three parameters:
   1. String
   2. Starting index of the string
   3. Ending index of the string. */
void permute(char *a, int i, int n) 
{
   int j; 
   if (i == n)
     printf("%s\n", a);
   else
   {
        for (j = i; j <= n; j++)
       {
          swap((a+i), (a+j));
          permute(a, i+1, n);
          swap((a+i), (a+j)); //backtrack
       }
   }


/* Driver program to test above functions */
int main()
{
  char *a;
  int i ,n;
  printf("enter number of elements ");
  scanf("%d",&n);
  a=(char *)malloc(n*sizeof(char));
  for(i=0;i<n;i++)
    {
      scanf(" %c",&a[i]);
    }
  permute(a,0,n-1);
   return 0;
}

No comments:

Post a Comment