# 146-c-sharp-program-for-permutation.html

Making all permutation of the given set of characters is most time effective if it is done with Heap’s algorithm. C# program for permutation with recursive function call in according to Heap’s algorithm is presented.

First thing that we need is to declare static public void function with two arguments:

• Integer that is equal to number of the characters to be permutated,
• Pointer to char array.

This is recursive function in C#, so it means that in code it has to call itself.

static public void permutations(int N, char[] Arr)

Every call is with smaller number of iteration until last iteration is equal to one. If it is equal to one, one permutation is generated and result has to be displayed. Otherwise, we need for loop that will do N steps, where in every step function call itself with argument N-1, and if N is odd number, first and last character should swap, or if N is even number, current character should swap with last one.

static public void permutations(int N, char[] Arr)
{

if (N == 1)
{

Console.WriteLine(new string(Arr));

}
else
{

for (int i = 0; i < N; i++)
{

permutations( N-1 , Arr);
if (N % 2 == 1)
{

// swap(0, n – 1);
char t = Arr[0];
Arr[0] = Arr[N-1];
Arr[N – 1] = t;

}
else
{

// swap(i, n – 1);
char t = Arr[i];
Arr[i] = Arr[N – 1];
Arr[N – 1] = t;

}

}

}

}

Main function should just convert input string into char array and then call function permutations.

static void Main(string[] args)
{

string str_input = “ABCDE”;
char[] chr_input = str_input.ToUpper().ToCharArray();
permutations(str_input.Length, chr_input);