三行快排

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
今天無意中在網上看到了一段用Python寫就的快速排序代碼,一共三行,簡稱三行快排。

-------------------------------------------------------------------------------------------------------


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


-------------------------------------------------------------------------------------------------------

倘若不算上函數的定義的話,一共就只剩下兩行代碼,首先就從對其代碼分析開始。
[x for x in L if x<L[0]]
這段代碼是python中常用的列表推導式,其作用就是對傳入的L進行分片,對小於L的第一個元素的值全部取出,形成一個新的列表,這個類表中的所有的元素全部小於L的第一個元素。

[x for x in L if x>L[0]]
這段代碼一樣,取出大於L的第一個元素的全部值,然後組成一個新的列表。

想必大家現在都很清楚了,這幾步實現的就是快排中的分治法的思想,將原列表分爲兩部分,一部分小於一個值,一部分大於這個值,然後把這個值放在兩個列表之間,那兩個列表進行遞歸操作就可以了。

當然,按照算法導論的觀點來看的話,這樣的排序未必是最優的,原因在於如果輸入的列表萬一是已經排好序的或者逆序平排好的,那麼時間複雜度就達不到理想的狀態了,解決的方法就是使算法隨機化。對於本例子中可以對L[0]進行處理,比如選取哪個元素進行隨機化處理,而不是像本例中規定了選擇第一個元素。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章