Bogo Sort Algorithm in Python

In this source code example, we will write a code to implement the Bogo Sort algorithm in Python.

In computer science, Bogo sort is a sorting algorithm based on the generating and test paradigm. The function successively generates permutations of its input until it finds one that is sorted. It is not considered useful for sorting but may be used for educational purposes, to contrast it with more efficient algorithms.

Bogo Sort Algorithm in Python

In this Python program, we will take input from the User or console and print the result to the output:
import random

def bogo_sort(collection):

    def is_sorted(collection):
        if len(collection) < 2:
            return True
        for i in range(len(collection) - 1):
            if collection[i] > collection[i + 1]:
                return False
        return True

    while not is_sorted(collection):
        random.shuffle(collection)
    return collection


if __name__ == "__main__":
    user_input = input("Enter numbers separated by a comma:\n").strip()
    unsorted = [int(item) for item in user_input.split(",")]
    print(bogo_sort(unsorted))

Output:

Enter numbers separated by a comma:
20, 10, 15, 25, 5
[5, 10, 15, 20, 25]

Related Algorithms in Python


Comments