w3resource
C# Sharp Programming Exercises

C# Sharp Searching and Sorting Algorithm Exercises: Permutation sort

C# Sharp Searching and Sorting Algorithm: Exercise-8 with Solution

Write a C# Sharp program to sort a list of elements using Permutation sort.

Permutation sort, proceeds by generating the possible permutations of the input array/list until discovering the sorted one.

Sample Solution:-

C# Sharp Code:

// https://bit.ly/2ABDdUZ
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
    private static void Swap(ref char a, ref char b)
    {
        if (a == b) return;

        a ^= b;
        b ^= a;
        a ^= b;
    }

    public static void GetPer(char[] list)
    {
        int x = list.Length - 1;
        GetPer(list, 0, x);
    }

    private static void GetPer(char[] list, int k, int m)
    {
        if (k == m)
        {
            {
                Console.WriteLine(list);
            }
            
           
        }
        else
            for (int i = k; i <= m; i++)
            {
                   Swap(ref list[k], ref list[i]);
                   GetPer(list, k + 1, m);
                   Swap(ref list[k], ref list[i]);
            }
    }

    static void Main()
    {
        string str = "ABC";
        char[] arr = str.ToCharArray();
        GetPer(arr);
    }
}

	

Sample Output:

ABC
ACB
BAC
BCA
CBA
CAB

Flowchart:

C# Sharp Searching and Sorting Algorithm Exercises: Permutation sort - Part-1

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C# Sharp program to sort a list of elements using Merge sort.
Next: Write a C# Sharp program to sort a list of elements using Quick sort.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming