in reply to Re^2: random #s
in thread random #s

Is this some sort of joke?

The algorithm you settled upon is known as a Bozosort, and is one of the algorithms studied in the infamous paper, Sorting the Slow Way: An Analysis of Perversely Awful Randomized Sorting Algorithms. That's right -- the algorithm that involves swapping random elements until the list is in order is considered not just awful, but perversely awful. "Perverse: showing a deliberate and obstinate desire to behave in a way that is unreasonable or unacceptable, often in spite of the consequences." .... that Perversely Awful -- So bad that one must be intentionally selecting the algorithm for its awfulness.

In that paper, this algorithm is shown to have an average run-time of O(n!), so in the case of your 20 numbers, on average it will take 432902008176640000 iterations to achieve a sorted solution. In the worst case it might never finish, since the solution is left to chance. In practical terms, as iterations increases toward infinity the probability of never finding a solution declines toward zero, meaning that if you are given infinite time a solution is virtually guaranteed. Who has infinite time?

If you are looking for an algorithm that is pretty simple to reason about, search for Bubble Sort. It's not terribly efficient, but it is also not perversely awful, and tends to be one of the easier sorting algorithms to comprehend and commit to code.


Dave

Replies are listed 'Best First'.
Re^4: random perversity
by hippo (Archbishop) on Oct 07, 2016 at 16:31 UTC

    cboPerl wants to sort some numbers without using sort. That's the very definition of perverse and there seems to be little point in offering any type of logical advice regarding such an endeavour.

      Sorting numbers without using sort is (in my eyes) a useful task in a beginners programming course. The student learns something about arrays here - and possibly something about algorithms and about partitioning a big problem (change the order of a huge list) into small steps (exchange two elements). So in my eyes it is far from being perverse.

      However the goal of the task is not reached if the student just copies some lines found in the internet. Speaking of this, I'm tempted to advise to use David Morgan-Mar's algorithm intelligent design sort - as it is easy to implement and very fast, especially for huge amounts of data.

      So long, Rata