Ahot's weblog

Thursday Oct 16, 2008

Just wondering how python works with arrays. Here is quick sort algorithm written in Python. Only one line of code:

def qsort(L):
    if L == []: return []
    return qsort([x for x in L[1:] if x< L[0]]) + L[0:1] + qsort([x for x in L[1:] if x>=L[0]])

Just to compare, how it looks in perl:
 #! /usr/bin/perl
 
 use strict;
 
 sub qsort {
     my ($q, $s, $e) = @_;
     my $m = $s-1;
     
     for (my $i = $s; $i < $e; $i++) {
         if ($q->[$i] < $q->[$e]) {
             $m++;
             ($q->[$m], $q->[$i]) = ($q->[$i], $q->[$m]);
         }
     }
     
     $m++;
     ($q->[$m], $q->[$e]) = ($q->[$e], $q->[$m]);
     qsort($q, $s, $m-1) if $s < $m-1;
     qsort($q, $m+1, $e) if $m+1 < $e;
 }
 
 my @data = map { int(rand(10)) } (1 .. 30);
 
 print "@data\n";
 qsort(\@data, 0, $#data);
 print "@data\n";

Comments:

i have never wrote any code like this in python.thank u for the idea!

Posted by Nima on February 28, 2009 at 02:34 PM GMT+03:00 #

Actualy idea is not mine.
I found the solution on wikipedia :)

Posted by ahot on March 30, 2009 at 10:44 PM GMT+03:00 #

Post a Comment:
  • HTML Syntax: NOT allowed

FEEDS:

BOOKMARKS:

This blog copyright 2010 by ahot