Bozo Sort
   HOME

TheInfoList



OR:

In
computer science Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to Applied science, practical discipli ...
, bogosort (also known as permutation sort, stupid sort, slowsort or bozosort) is a
sorting algorithm In computer science, a sorting algorithm is an algorithm that puts elements of a List (computing), list into an Total order, order. The most frequently used orders are numerical order and lexicographical order, and either ascending or descending. ...
based on the
generate and test Trial and error is a fundamental method of problem-solving characterized by repeated, varied attempts which are continued until success, or until the practicer stops trying. According to W.H. Thorpe, the term was devised by C. Lloyd Morgan (1 ...
paradigm. The function successively generates
permutation In mathematics, a permutation of a set is, loosely speaking, an arrangement of its members into a sequence or linear order, or if the set is already ordered, a rearrangement of its elements. The word "permutation" also refers to the act or proc ...
s 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. Two versions of this algorithm exist: a deterministic version that enumerates all permutations until it hits a sorted one,. and a
randomized In common usage, randomness is the apparent or actual lack of pattern or predictability in events. A random sequence of events, symbols or steps often has no order and does not follow an intelligible pattern or combination. Individual rand ...
version that randomly permutes its input. An analogy for the working of the latter version is to sort a
deck of cards A playing card is a piece of specially prepared card stock, heavy paper, thin cardboard, plastic-coated paper, cotton-paper blend, or thin plastic that is marked with distinguishing motifs. Often the front (face) and back of each card has a fi ...
by throwing the deck into the air, picking the cards up at random, and repeating the process until the deck is sorted. Its name is a
portmanteau A portmanteau word, or portmanteau (, ) is a blend of wordspseudocode In computer science, pseudocode is a plain language description of the steps in an algorithm or another system. Pseudocode often uses structural conventions of a normal programming language, but is intended for human reading rather than machine re ...
: while not sorted(deck): shuffle(deck) Here is the above pseudocode rewritten in
Python 3 The programming language Python was conceived in the late 1980s, and its implementation was started in December 1989 by Guido van Rossum at CWI in the Netherlands as a successor to ABC capable of exception handling and interfacing with the ...
: from random import shuffle def is_sorted(data) -> bool: """Determine whether the data is sorted.""" return all(a <= b for a, b in zip(data, data :) def bogosort(data) -> list: """Shuffle data until sorted.""" while not is_sorted(data): shuffle(data) return data This code assumes that is a simple, mutable, array-like data structure—like Python's built-in —whose elements can be compared without issue.


Running time and termination

If all elements to be sorted are distinct, the expected number of comparisons performed in the average case by randomized bogosort is asymptotically equivalent to , and the expected number of swaps in the average case equals .. The expected number of swaps grows faster than the expected number of comparisons, because if the elements are not in order, this will usually be discovered after only a few comparisons, no matter how many elements there are; but the work of shuffling the collection is proportional to its size. In the worst case, the number of comparisons and swaps are both unbounded, for the same reason that a tossed coin might turn up heads any number of times in a row. The best case occurs if the list as given is already sorted; in this case the expected number of comparisons is , and no swaps at all are carried out. For any collection of fixed size, the expected running time of the algorithm is finite for much the same reason that the
infinite monkey theorem The infinite monkey theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type any given text, such as the complete works of William Shakespeare. In fact, the monkey would ...
holds: there is some probability of getting the right permutation, so given an unbounded number of tries it will
almost surely In probability theory, an event is said to happen almost surely (sometimes abbreviated as a.s.) if it happens with probability 1 (or Lebesgue measure 1). In other words, the set of possible exceptions may be non-empty, but it has probability 0. ...
eventually be chosen.


Related algorithms

;: is a sorting algorithm introduced in the 2011
Google Code Jam Google Code Jam is an international programming competition hosted and administered by Google. The competition began in 2003. The competition consists of a set of algorithmic problems which must be solved in a fixed amount of time. Competitors ...
. As long as the list is not in order, a subset of all elements is randomly permuted. If this subset is optimally chosen each time this is performed, the
expected value In probability theory, the expected value (also called expectation, expectancy, mathematical expectation, mean, average, or first moment) is a generalization of the weighted average. Informally, the expected value is the arithmetic mean of a l ...
of the total number of times this operation needs to be done is equal to the number of misplaced elements. ;: is an algorithm that was designed not to succeed before the
heat death of the universe The heat death of the universe (also known as the Big Chill or Big Freeze) is a hypothesis on the ultimate fate of the universe, which suggests the universe will evolve to a state of no thermodynamic free energy, and will therefore be unabl ...
on any sizable list. It works by recursively calling itself with smaller and smaller copies of the beginning of the list to see if they are sorted. The base case is a single element, which is always sorted. For other cases, it compares the last element to the maximum element from the previous elements in the list. If the last element is greater or equal, it checks if the order of the copy matches the previous version, and if so returns. Otherwise, it reshuffles the current copy of the list and restarts its recursive check. ;: is another sorting algorithm based on random numbers. If the list is not in order, it picks two items at random and swaps them, then checks to see if the list is sorted. The running time analysis of a bozosort is more difficult, but some estimates are found in H. Gruber's analysis of "perversely awful" randomized sorting algorithms. is found to be the expected average case. ;: is a pessimal sorting algorithm that is guaranteed to complete in finite time; however, its efficiency can be arbitrarily bad, depending on its configuration. The algorithm is based on a bad sorting algorithm, . The badsort algorithm accepts two parameters: , which is the list to be sorted, and , which is a recursion depth. At recursion level , merely uses a common sorting algorithm, such as
bubblesort Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the input list element by element, comparing the current element with the one after it, swapping their values if needed. These passes ...
, to sort its inputs and return the sorted list. That is to say, . Therefore, badsort's time complexity is if . However, for any , first generates , the list of all permutations of . Then, calculates , and returns the first element of the sorted . To make truly pessimal, may be assigned to the value of a computable increasing function such as f\colon\N \to \N (e.g. , where is
Ackermann's function In computability theory, the Ackermann function, named after Wilhelm Ackermann, is one of the simplest and earliest-discovered examples of a total computable function that is not primitive recursive. All primitive recursive functions are total a ...
). Ergo, to sort a list arbitrarily badly, you would execute , where is the number of elements in . The resulting algorithm has complexity \Omega\left(\left(n!^\right)^2\right), where n!^ = (\dotso((n!)!)!\dotso)! = factorial of iterated times. This algorithm can be made as inefficient as one wishes by picking a fast enough growing function . ;
Slowsort Slowsort is a sorting algorithm. It is of humorous nature and not useful. It is a ''reluctant algorithm'' based on the principle of ''multiply and surrender'' (a parody formed by taking the opposites of '' divide and conquer''). It was published i ...
: is a different humorous sorting algorithm that employs a misguided divide-and-conquer strategy to achieve massive complexity. ;: is a hypothetical sorting algorithm based on bogosort, created as an
in-joke An in-joke, also known as an inside joke or a private joke, is a joke whose humour is understandable only to members of an ingroup; that is, people who are ''in'' a particular social group, occupation, or other community of shared interest. It i ...
among computer scientists. The algorithm generates a random permutation of its input using a quantum source of entropy, checks if the list is sorted, and, if it is not, destroys the universe. Assuming that the
many-worlds interpretation The many-worlds interpretation (MWI) is an interpretation of quantum mechanics that asserts that the universal wavefunction is objectively real, and that there is no wave function collapse. This implies that all possible outcomes of quantum me ...
holds, the use of this algorithm will result in at least one surviving universe where the input was successfully sorted in time. ;: is a sorting algorithm that checks if the array is sorted until a
miracle A miracle is an event that is inexplicable by natural or scientific lawsOne dictionary define"Miracle"as: "A surprising and welcome event that is not explicable by natural or scientific laws and is therefore considered to be the work of a divin ...
occurs. It continually checks the array until it is sorted, never changing the order of the array. Because the order is never altered, the algorithm has a hypothetical time complexity of , but it can still sort through events such as miracles or single-event upsets. Particular care must be taken in the implementation of this algorithm as
optimizing compiler In computing, an optimizing compiler is a compiler that tries to minimize or maximize some attributes of an executable computer program. Common requirements are to minimize a program's execution time, memory footprint, storage size, and power cons ...
s may simply transform it into a
while(true) In computer programming, an infinite loop (or endless loop) is a sequence of instructions that, as written, will continue endlessly, unless an external intervention occurs ("pull the plug"). It may be intentional. Overview This differs from: * ...
loop.


See also

*
Las Vegas algorithm In computing, a Las Vegas algorithm is a randomized algorithm that always gives correct results; that is, it always produces the correct result or it informs about the failure. However, the runtime of a Las Vegas algorithm differs depending on the ...
*
Stooge sort Stooge sort is a recursive sorting algorithm. It is notable for its exceptionally bad time complexity of . The running time of the algorithm is thus slower compared to reasonable sorting algorithms, and is slower than bubble sort, a canonical exa ...


Notes


References


External links

*
BogoSort In computer science, bogosort (also known as permutation sort, stupid sort, slowsort or bozosort) is a sorting algorithm based on the generate and test paradigm. The function successively generates permutations of its input until it finds one th ...
on
WikiWikiWeb The WikiWikiWeb is the first wiki, or user-editable website. It was launched on 25 March 1995 by programmer Ward Cunningham to accompany the Portland Pattern Repository website discussing software design patterns. The name ''WikiWikiWeb'' origi ...

Inefficient sort algorithms

Bogosort
an implementation that runs on
Unix-like A Unix-like (sometimes referred to as UN*X or *nix) operating system is one that behaves in a manner similar to a Unix system, although not necessarily conforming to or being certified to any version of the Single UNIX Specification. A Unix-li ...
systems, similar to the standard
sort Sort may refer to: * Sorting, any process of arranging items in sequence or in sets ** Sorting algorithm, any algorithm for arranging elements in lists ** Sort (Unix), a Unix utility which sorts the lines of a file ** Sort (C++), a function in the ...
program.
Bogosort
an
jmmcg::bogosort
Simple, yet perverse, C++ implementations of the bogosort algorithm.
Bogosort NPM package
bogosort implementation for Node.js ecosystem. * Max Sherma
Bogo-sort is Sort of Slow
June 2013 {{sorting Sorting algorithms Comparison sorts Computer humor Articles with example Python (programming language) code