Wednesday, 27 July 2011

Permuting a String.


Write a C program to print all permutations of a given string ?

For Ex: The Permutation of string "ABC" are "ABC, ACB, BAC, BCA, CAB, CBA"

Program: (using backtracking)

# include <stdio.h>
# include <conio.h>
void swap (char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
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
       }
   }
}

void main()
{
   char a[] = "ABC";
   clrscr();
   permute(a, 0, 2);
   getch();
}

No comments:

Post a Comment