您的位置:首页 > 编程语言 > Python开发

快速排序法的python实现

2016-11-17 00:00 113 查看
摘要: python,快速排序法

快速排序法是最常用的排序法之一,下面用简单的python程序实现,并做验证。

quicksort.py

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

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)

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)

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

下面是程序的运行验证。

[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


结论:

快速排序法具有极好的性能表现,尤其适合大数据排序中的应用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 快速排序法