login


Quick Sort in python

Tuesday, May. 19. 2009 –  Category: Pythonic  –  0 Comments
Tags: python  sort  algorithm 

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]])



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


# IMHO this is almost as nice as the Haskell version from www.haskell.org:
# qsort [] = []
# qsort (x:xs) = qsort elts_lt_x ++ [x] ++ qsort elts_greq_x
# where
# elts_lt_x = [y | y <- xs, y < x]
# elts_greq_x = [y | y <- xs, y >= x]

# And here's a test function:
def qs_test(length):
import random
joe = range(length)
random.shuffle(joe)
qsJoe = qsort(joe)
for i in range(len(qsJoe)):
assert qsJoe[i] == i, 'qsort is broken!'


def qs(ds):
if len(ds) <= 1: return ds
pivot = random.choice(ds)
return qs(filter(lambda x: x < pivot, ds)) +
[pivot]*ds.count(pivot) +
qs(filter(lambda x: x > pivot, ds))


Just For Fun: Quicksort in 1 Line. Of course this must not be used in real code too!


q=lambda x:(lambda o=lambda s:[i for i in x if cmp(i,x[0])==s]:len(x)>1 and q(o(-1))+o(0)+q(o(1)) or x)()

This lambda expression is just a rewriting of this function:

def q(x):
if len(x)>1:
lt = [i for i in x if cmp(i,x[0]) == -1 ]
eq = [i for i in x if cmp(i,x[0]) == 0 ]
gt = [i for i in x if cmp(i,x[0]) == 1 ]
return q(lt) + q(eq) + q(gt)
else:
return x


from random import randrange
def qsort1a(list):
"""
Quicksort using list comprehensions and randomized pivot
>>> qsort1a<>
<>
>>> qsort1a<>
<>
"""

def qsort(list):
if list == []:
return []
else:
pivot = list.pop(randrange(len(list)))
lesser = qsort([l for l in list if l < pivot])
greater = qsort([l for l in list if l >= pivot])
return lesser + [pivot] + greater
return qsort(list[:])

========================================================================================




    Share in Google Reader     Share in Twitter..     Share in Friendfeed     Leave a Reply

0 Response to “Quick Sort in python”

Leave a Reply


Logo

About Me

  • A Computer Geek in Beijing, China. Focus on Web2.0 Technology: Google App Engine, Python, Django, Software Architecture, Agile, JAVA, J2EE, JavaScript, etc.

    Coding for fun, Coding with passion :-) It's my life!

Most Popular Posts

Tags