top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to find all permutations of a given string?

+3 votes
1,044 views

Say the given string is ABC

Output should be ABC ACB BAC BCA CBA CAB

posted Nov 28, 2013 by Neelam

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes

This is a very famous question, You can find answer easily in internet...

# include <stdio.h>

/* Function to swap values at two pointers */
void swap (char *x, char *y)
{
    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[] = "ABC";  
   permute(a, 0, 2);
   getchar();
   return 0;
}

For complete explanation visit this site..
Credits : GeeksforGeeks

answer Nov 28, 2013 by Raghu
Thanks Raghu :)
...