We have worked with sorted lists for many different problems. We have used built-in functions to sort some arrays. Yet, itβs not obvious how those built-in functions actually work under the hood. In this chapter, weβll discuss some of the most popular sorting algorithms that are used in different places - depending on the application.
The first algorithm weβll discuss is the most ridiculous of all of the sorting algorithms. Itβs called Bogosort. Itβs not used anywhere in real-world applications, and youβll soon see why.
Given n numbers, the algorithm works by randomly shuffling those numbers and then checking if the resulting list is sorted:
from random import shuffle
a = [3, 1, -2, 5, 6] # Initial numbers
while True: # Loop until the array is sorted
is_sorted = True
for i in range(1, len(a)): # A loop to check if the array is sorted
if a[i] < a[i-1]: # If we find an element smaller then previous => it's not sorted
is_sorted = False # We set the variable to False and stop the loop
break
if is_sorted: # If the array is sorted => stop the infinite loop
break
else: # Otherwise shuffle the list again
shuffle(a)
print(a) # Finally print the resulting list
This algorithm is random and it can take infinitely long to complete. Therefore, it would be really dangerous and inefficient to use something like this in production applications.
You are asked to compute the number of iterations it would take for a Bogosort algorithm to finally find a solution.
Input
The first line of the input contains a single integer n (1 β€ n β€ ).
The next line contains n space-separated integers ( β€ β€ ).
Output
The program should print the number of iterations it would take the Bogosort algorithm to complete the search.
Examples
Input
Output
5
5 -1 2 3 9
10
Explanation
The number 10 is a random number - it couldβve been 2, or 200. You might get different numbers when running the same program on the same input several times.
Β
Other Ridiculous Sorting Algorithms
You can find other visualized sorting algorithms in the YouTube video below created by Ardens.