Tuesday, July 09, 2013

Perl - Quicksort


We all know that quicksort is a divide and conquer algorithm. It first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists. On average, it makes O(n log n) comparisons to sort n items. In the worst case, it makes O(n^2) comparisons, though this behavior is rare. Quicksort is often faster in practice than other O(n log n) algorithms

The steps are:


  1. Pick an element, called a pivot, from the list.
  2. Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.    
  3. Recursively apply the above steps to the sub-list of elements with smaller values and separately the sub-list of elements with greater values.


Quick sort worst case time complexity occur when pivot produces two regions one of size 1 element and other of size (n-1) elements recursively.Whereas average case occurs when pivot chooses two regions such that both regions produced have a size of n/2. 

So recursive relation produced is T(n)=2T(n/2)+Θ(n).

f(n)=Θ(n)    
h(n)=n^log2(2)=>n
since f(n) = h(n) so
T(n)= f(n)logn =>n(logn).

(here we are using Θ notation since worst case complexity(big O) of quick sort is O(n^2) and here we are calculating average case complexity.)

Here is a piece of perl code that implementing quicksort:

#!/usr/bin/perl
use strict;
use warnings;

my @a = (9,8,2,3,4,5,7);
@a = quicksort(@a);
print "@a\n";

my $counter = 0;

sub quicksort {
    print "@_\n";
    @_ <= 1 ? @_ : do  {     # If the whole array only has 1 element, return, beacuse it is already sorted.
        my $pivot = pop;     # get a pivot
        quicksort( grep {$_ <= $pivot} @_ ),
        $pivot,
        quicksort( grep {$_ >  $pivot} @_ )
    }
}
Reference:http://blogs.perl.org/users/pid/2011/02/the-beauty-of-a-perl-quicksort.html

No comments: