Keep It Simple, Stupid | |
PerlMonks |
Re: Pugs now works - but how?by pernod (Chaplain) |
on Feb 18, 2005 at 22:56 UTC ( [id://432561]=note: print w/replies, xml ) | Need Help?? |
Can someone explain me very briefly how the code in the reply of autrijus (It now works. :)) operates? I'll give it a shot :)
I'll assume you're familiar with the quicksort algorithm already, and the way it uses pivots. The first line states how we sort an empty list. Which is simply to return the empty list. This serves as the case for breaking recursion and avoiding infinite looping. Line two defines a head and a tail, where the head $x is the first element in the list ('1' in the case of the call at line 7), while the tail @xs contains the remaining elements. Line 3 declares a list which contains all the elements from the tail that have a value smaller than $x. @pre = @xs.grep{ $_ < $x } applies the built-in function grep to the tail. grep returns only the elements in @xs that are smaller than $x and puts them into @pre. This list is still unordered, but we now know that all the values in @pre are smaller than the pivot $x. Similarily for @post, but here we have all the bigger elements. The magic kicks in at line 5, where we assemble the parts into a new list with the pivot in the middle. Remember though, that @pre and @post are as yet unsorted, so we apply quicksort to them recursively before we return the concatenated list. Line 7 applies quicksort to a list, and then prints it to screen with the say. Say, I presume, is something similar to Haskell's show and Java's toString(). Clear as ink :D pernod
In Section
Seekers of Perl Wisdom
|
|