Everytime someone posts a question about bubble sorts, someone else points out that bubble sorts are "the worst sorting algorithm possible", being O(n^2).

Of course, we can do much worst than O(n^2). I present here a much better candidate for "the worst", the splatter sort, which will take on average O(n!). (Well, O(m!), where m is the number of distinct values among the n elements.)

This algorithm was inspired by many student assignments back when I was a corrector in university, where the student would do

while(list_isnt_sorted()) {
  do_buggy_transform();
}
and claim their code was right because it eventually terminated with a sorted list...

A more advanced version would use a code ref to pass to is_sorted, so we could have different sort criteria like perl's sort routine does...

Just when you thought sorts couldn't get any worst :)

(Edit: D'oh! This isn't as bad as it could be. Since I check if the list is sorted before shuffling, this will unfortunately do quite well on already sorted data. Pessimizing the code further isn't too challenging an exercise, though :) )

# stolen from sauoq, who attributed it to perdoc -q shuffle: sub fisher_yates_shuffle { my $deck = shift; # $deck is a reference to an array my $i = @$deck; while ($i--) { my $j = int rand ($i+1); @$deck[$i,$j] = @$deck[$j,$i]; } } sub is_sorted { my $list_r = shift; my $prev=$list_r->[0]; for(my $i=1;$i<scalar @$list_r;++$i) { return 0 if $list_r->[$i]<$prev; $prev=$list_r->[$i]; } return 1; } # sort list passed by reference in place, returning # reference to sorted list # # takes n! time. sub splatter_sort { my $list_r=shift; while(!is_sorted($list_r)) { fisher_yates_shuffle($list_r); } return $list_r; }

In reply to Making bubble sort look good by RMGir

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.