June 29, 2011

String Permutation

Question: Write a program to display all permutation of alphabets in the string ? For example: string 'xyz' has following possible permutations:
xyz
xzy
yxz
yzx
zxy
zyx


// initial call: permutations("xyz", 0)
void permutations(char *str, int level)
{
    int i = 0;
    int len = strlen(str);<br>
    if (level == len)
    {
        // Termination Condition
        printf("%s\n", output);
        return;
    }


    for (i = 0; i < len; i++)
    {
        if (flag[i]) continue;
        output[level] = str[i];
        flag[i] = 1;
        permutations(str, level + 1);
        flag[i] = 0;
    }
}

No comments:

Post a Comment