Quick Sort in python
Tuesday, May. 19. 2009 –
Category: Pythonic –
0 Comments
Tags:
python
sort
algorithm
Quick Sort in python
https://docs.google.com/Doc?docid=dftf9bqn_33c2jqjxg7&hl=en
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))
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[:])
========================================================================================
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
- 1. GAE限制续 (1964)
- 2. Eclipse Google Plugin安装指南 (1785)
- 3. iHere Blog 1.0.2 安装配置 (1658)
- 4. iHere Blog 安装 简要配置 (1386)
- 5. 终于在做导入的时候遇到了GAE的瓶颈 (1158)
- 6. 新加Ajax效果Page flow (1015)
- 7. GAE上面的Unittest总结 (1000)
- 8. 新东西 呵呵 JS3D (961)
- 9. Web Python IDE Py I/O release! (945)
- 10. 转向了Appengine patch (937)
Tags
-
App Engine
Appengine patch
Django
Google
Google App Engine
Google App Engine
Java
algorithm
api
app
appengine
autodiscovery
blog
cache
chat
cloud computing
cron jobs
datastore
demo
feature
fetion
fridge
gae
geo
google
google app engine
google docs
googlemaps
iHere Blog History
ide
ihere
inforsphere
install
java
jquery
map
mashup
memcache
metaweblog
new
nutch
open source
pageflow
plugin
projects
pyio
python
quota
release
released
rss
sdk
snap
sort
topStory
twitter
weblog api
杂记


Just For Fun: Quicksort in 1 Line. Of course this must not be used in real code too!
This lambda expression is just a rewriting of this function: