Random sorting (Bogosort) is one of the most inefficient array sorting algorithms.

Bogosort Algorithm Description

The random sorting algorithm is as follows: first, the array is checked for ordering, if the elements are not sorted, then we randomly mix them and check again, the operations are repeated until the array is sorted.

Implementing random sorting

using System;

class program
{
    // method for checking array ordering
    static bool IsSorted(int[] a)
    {
        for (int i = 0; i < a.Length - 1; i++)
        {
            if (a[i] > a[i + 1])
                return false;
        }

        return true;
    }

    // shuffle array elements
    static int[] RandomPermutation(int[] a)
    {
        Random random = new Random();
        var n = a.Length;
        while (n > 1)
        {
            n--;
            var i = random.Next(n + 1);
            var temp = a[i];
            a[i] = a[n];
            a[n] = temp;
        }

        return a;
    }

    // random sort
    static int[] BogoSort(int[] a)
    {
        while (!IsSorted(a))
        {
            a = RandomPermutation(a);
        }

        return a;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Random Sort");
        Console.Write("Enter elements of the array:");
        var parts = Console.ReadLine().Split(new[] { "", ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
        var array = new int[parts.Length];
        for (int i = 0; i < parts.Length; i++)
        {
            array[i] = Convert.ToInt32(parts[i]);
        }

        Console.WriteLine("Sorted array: {0}", string.Join(",", BogoSort(array)));

        Console.ReadLine();
    }
}

The result of the program:

Related pages: