Page Actions
Wiki Actions
User Actions
Submit This Story

对Python List 进行 quick sort ...

挺让我意外的Python list comprehensions… 简单,自然的List QuickSort实现:

The Code

from random import randrange       
def qsortlist(list):
    """
    Quicksort using list comprehensions and randomized pivot
    """
    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[:])

感想

如此清晰,简便的快速排序…虽然性能肯定远不如一般的C,C++之类的实现,但是鉴于这是针对list的排序,应用广阔而方便,python的数字计算能力也不差, 又有不错的随机数生成器。 C的话要提供比较方法,C++的话要用模板类来推广,而我自认为C/C++水平远不及Python解释器. C的那些存储,赋值,等小数据处理操作一不小心性能就被拉下去了… 所以懒惰的我觉得这也算是挺实用的,比如英文姓名排序…

Discussion

Hippie, 2012/01/08 20:53

Holy cocnsie data batman. Lol!

Enter your comment
 
 
blog/2009/10/对python_list_进行_quick_sort.txt · Last modified: 2009/10/01 00:00 (external edit)     Back to top
Recent changes RSS feed Creative Commons License Powered by PHP Driven by DokuWiki