Find all permutations of a String

Given a string, find all the permutations of the string.
For example:
Input String: abc
Output: {bca, acb, abc, cba, bac, cab}

Program:

class Program
    {
        /*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.*/
        private static void permute(String str, int l, int r)
        {
            if (l == r)
                Console.WriteLine(str);
            else
            {
                for (int i = l; i <= r; i++)
                {
                    str = swap(str, l, i);
                    permute(str, l + 1, r);
                    str = swap(str, l, i);
                }
            }
        }

        //Function to swap values 
        public static String swap(String a, int i, int j)
        {
            char temp;
            char[] charArray = a.ToCharArray();
            temp = charArray[i];
            charArray[i] = charArray[j];
            charArray[j] = temp;
            string s = new string(charArray);
            return s;
        }

        static void Main(string[] args)
        {
            String str = "ABC";
            int n = str.Length;
            permute(str, 0, n - 1);
            Console.ReadLine();
        }
    }

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *