快速排序法的python實現

快速排序法是最經常使用的排序法之一,下面用簡單的python程序實現,並作驗證。python

quicksort.pyapp

#!/usr/local/bin/python3.5 -udom

import sys
import random
性能

def generateRandomList(n):
    list = []
    for i in range(n):
        list.append(random.randint(0, n*10))
    return(list)
測試

def partition(list):
    i = 0
    x = list[len(list)-1]
    for j in range(len(list)):
        if list[j] < x:
            (list[i], list[j]) = (list[j], list[i])
            i += 1
    (list[i], list[len(list)-1]) = (list[len(list)-1], list[i])
    return(i, list)
大數據

def quicksort(list):
    if len(list)>1:
        (q, list) = partition(list)
        list[0:q] = quicksort(list[0: q])
        list[q+1:] = quicksort(list[q+1:])
    return(list)
ui

def main():
    list = generateRandomList(30)
    print("Generate an random unsorted list :")
    print(list)
    sortedList = quicksort(list)
    print("")
    print("Sort it with quick-sort :")
    print(sortedList)
spa


###################
## Main Function ##
###################
if __name__ == "__main__":
    main()
排序

 

下面是程序的運行驗證。it

[liyanqing@bogon python]$ ./quicksort.py
Generate an random unsorted list :
[287, 42, 13, 122, 211, 64, 191, 147, 262, 197, 191, 280, 198, 179, 55, 122, 63, 266, 101, 133, 17, 196, 293, 153, 1, 211, 59, 197, 138, 271]

Sort it with quick-sort :
[1, 13, 17, 42, 55, 59, 63, 64, 101, 122, 122, 133, 138, 147, 153, 179, 191, 191, 196, 197, 197, 198, 211, 211, 262, 266, 271, 280, 287, 293]
[liyanqing@bogon python]$ ./quicksort.py
Generate an random unsorted list :
[2, 80, 270, 115, 268, 85, 36, 110, 194, 1, 122, 69, 300, 286, 106, 221, 281, 121, 237, 19, 22, 51, 264, 278, 174, 296, 289, 163, 138, 298]

Sort it with quick-sort :
[1, 2, 19, 22, 36, 51, 69, 80, 85, 106, 110, 115, 121, 122, 138, 163, 174, 194, 221, 237, 264, 268, 270, 278, 281, 286, 289, 296, 298, 300]
[liyanqing@bogon python]$ ./quicksort.py
Generate an random unsorted list :
[93, 239, 255, 79, 62, 145, 298, 65, 11, 79, 139, 228, 253, 31, 248, 244, 256, 298, 193, 165, 284, 33, 144, 34, 61, 182, 74, 171, 36, 259]

Sort it with quick-sort :
[11, 31, 33, 34, 36, 61, 62, 65, 74, 79, 79, 93, 139, 144, 145, 165, 171, 182, 193, 228, 239, 244, 248, 253, 255, 256, 259, 284, 298, 298]

 

爲測試其性能,將隨機生成的無序列表長度調整爲1000000,其仍然具備較快的速度。

[liyanqing@bogon python]$ time ./quicksort.py

... ...

real    0m10.939s
user    0m8.861s
sys    0m0.116s

 

結論:

快速排序法具備極好的性能表現,尤爲適合大數據排序中的應用。

相關文章
相關標籤/搜索