Monday, February 13, 2012

Print all permutation

Although it's just a program (algorithm) , but I took lot of time to solve this. So, feel worth to post it here.

Question : given a string like 'abc' print all combinations
ans,  :  abc acb bac bca cab cba


============


void printall(char *str, char *ptr)
{
if (*(ptr+1) == '\0')
{
cout << str << endl;
}
else
{
for (char* swap = ptr; *swap != '\0'; ++swap)
{
char temp = *swap;
*swap = *ptr;
*ptr = temp;

printall(str, ptr+1);

temp = *ptr;
*ptr = *swap;
*swap = temp;
}
}
}

int main(int argc, char **argv)
{
char str[2056] = "abcd";
printall(str, str);
}