Print all permutations of given string

Write a program to Print all permutations of given string

For Example

Input:
abc

Output:
abc
acb
bac
bca
cba
cab

Solution:

using System;
namespace permutationsstring
{
    class Program
    {
        public static void Main()
        {
            var str = "abc";
            Permutations(str, 0, str.Length - 1);
            Console.ReadLine();
        }

        private static void Permutations(string str, int l, int r)
        {
            if (l == r)
                Console.WriteLine(str);
            else
            {
                for (var i = l; i <= r; i++)
                {
                    str = Swap(str, l, i);
                    Permutations(str, l + 1, r);
                    str = Swap(str, l, i);
                }
            }
        }

        static string Swap(string str, int i, int j)    
        {
            var charArray = str.ToCharArray();
            var temp = charArray[i];
            charArray[i] = charArray[j];
            charArray[j] = temp;
            return new string(charArray);
        }
    }
}

Leave a Reply

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