w3resource

C#: Bogosort

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

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

In computer science, bogosort is a particularly ineffective sorting algorithm based on the generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted. It is not useful for sorting, but may be used for educational purposes, to contrast it with other more realistic algorithms.
Two versions of the algorithm exist: a deterministic version that enumerates all permutations until it hits a sorted one, and a randomized version that randomly permutes its input. An analogy for the working of the latter version is to sort a deck of cards by throwing the deck into the air, picking the cards up at random, and repeating the process until the deck is sorted. Its name comes from the word bogus.

Sample Solution:

C# Sharp Code:

using System;
using System.Collections.Generic;

namespace Bogo_sort
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initializing an unsorted list of integers
            List<int> list = new List<int>() { 2, 1, 3, 0 };
            Console.WriteLine("Sorting...");
            // Calling the Bogo_sort function with optional parameters (announce and delay)
            Bogo_sort(list, true, 5);
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }

        // Function to perform Bogo sort
        static void Bogo_sort(List<int> list, bool announce, int delay)
        {
            int iteration = 0;
            // Loop until the list is sorted
            while (!IsSorted(list))
            {
                if (announce)
                {
                    // Print the current iteration if announce is set to true
                    Print_Iteration(list, iteration);
                }
                if (delay != 0)
                {
                    // Introduce a delay if delay parameter is non-zero
                    System.Threading.Thread.Sleep(Math.Abs(delay));
                }
                // Rearrange the list elements randomly
                list = Remap(list);
                iteration++; // Increment iteration count
            }

            Print_Iteration(list, iteration); // Print the final sorted list
            Console.WriteLine();
            Console.WriteLine("Bogo_sort completed after {0} iterations.", iteration); // Display the total iterations
        }

        // Function to print the current iteration of the list
        static void Print_Iteration(List<int> list, int iteration)
        {
            Console.Write("Bogo_sort iteration {0}: ", iteration);
            for (int i = 0; i < list.Count; i++)
            {
                Console.Write(list[i]);
                if (i < list.Count)
                {
                    Console.Write(" ");
                }
            }
            Console.WriteLine();
        }

        // Function to check if the list is sorted
        static bool IsSorted(List<int> list)
        {
            for (int i = 0; i < list.Count - 1; i++)
            {
                if (list[i] > list[i + 1])
                {
                    return false; // Returns false if the list is not sorted
                }
            }

            return true; // Returns true if the list is sorted
        }

        // Function to rearrange the list elements randomly
        static List<int> Remap(List<int> list)
        {
            int temp;
            List<int> newList = new List<int>();
            Random r = new Random();

            // Randomly rearrange elements from the input list to a new list
            while (list.Count > 0)
            {
                temp = (int)r.Next(list.Count);
                newList.Add(list[temp]);
                list.RemoveAt(temp);
            }
            return newList; // Return the new list with rearranged elements
        }
    }
}

Sample Output:

Sorting...                                                                                                    
Bogo_sort iteration 0: 2 1 3 0                                                                                
Bogo_sort iteration 1: 3 1 0 2                                                                                
Bogo_sort iteration 2: 1 2 3 0                                                                                
Bogo_sort iteration 3: 0 2 3 1                                                                                
Bogo_sort iteration 4: 2 1 0 3                                                                                
Bogo_sort iteration 5: 2 0 3 1                                                                                
Bogo_sort iteration 6: 3 1 2 0                                                                                
Bogo_sort iteration 7: 1 3 0 2                                                                                
Bogo_sort iteration 8: 2 0 1 3                                                                                
Bogo_sort iteration 9: 1 2 3 0                                                                                
Bogo_sort iteration 10: 1 0 2 3  
----
Bogo_sort iteration 38: 1 0 3 2                                                                               
Bogo_sort iteration 39: 0 1 2 3                                                                               
                                                                                                              
Bogo_sort completed after 39 iterations.                                                                      
Press any key to exit.

Flowchart:

C# Sharp Searching and Sorting Algorithm Exercises: Bogosort.

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.