【发布时间】:2011-02-10 23:40:06
【问题描述】:
我正在用 Python 乱搞,试图练习我的排序算法并发现了一些有趣的东西。
我有三个不同的数据:
- x = 要排序的数字数
- y = 数字所在的范围(所有随机生成的整数)
- z = 排序总时间
时间:
x = 100000 和
y = (0,100000) 然后
z = 0.94182094911 秒
时间:
x = 100000 和
y = (0,100) 然后
z = 12.4218382537 秒
时间:
x = 100000 和
y = (0,10) 然后
z = 110.267447809 秒
有什么想法吗?
代码:
import time
import random
import sys
#-----Function definitions
def quickSort(array): #random pivot location quicksort. uses extra memory.
smaller = []
greater = []
if len(array) <= 1:
return array
pivotVal = array[random.randint(0, len(array)-1)]
array.remove(pivotVal)
for items in array:
if items <= pivotVal:
smaller.append(items)
else:
greater.append(items)
return concat(quickSort(smaller), pivotVal, quickSort(greater))
def concat(before, pivot, after):
new = []
for items in before:
new.append(items)
new.append(pivot)
for things in after:
new.append(things)
return new
#-----Variable definitions
list = []
iter = 0
sys.setrecursionlimit(20000)
start = time.clock() #start the clock
#-----Generate the list of numbers to sort
while(iter < 100000):
list.append(random.randint(0,10)) #modify this to change sorting speed
iter = iter + 1
timetogenerate = time.clock() - start #current timer - last timer snapshot
#-----Sort the list of numbers
list = quickSort(list)
timetosort = time.clock() - timetogenerate #current timer - last timer snapshot
#-----Write the list of numbers
file = open("C:\output.txt", 'w')
for items in list:
file.write(str(items))
file.write("\n")
file.close()
timetowrite = time.clock() - timetosort #current timer - last timer snapshot
#-----Print info
print "time to start: " + str(start)
print "time to generate: " + str(timetogenerate)
print "time to sort: " + str(timetosort)
print "time to write: " + str(timetowrite)
totaltime = timetogenerate + timetosort + start
print "total time: " + str(totaltime)
--------修改了新代码------------------------- ---
def quickSort(array): #random pivot location quicksort. uses extra memory.
smaller = []
greater = []
equal = []
if len(array) <= 1:
return array
pivotVal = array[random.randint(0, len(array)-1)]
array.remove(pivotVal)
equal.append(pivotVal)
for items in array:
if items < pivotVal:
smaller.append(items)
elif items > pivotVal:
greater.append(items)
else:
equal.append(items)
return concat(quickSort(smaller), equal, quickSort(greater))
def concat(before, equal, after):
new = []
for items in before:
new.append(items)
for items in equal:
new.append(items)
for items in after:
new.append(items)
return new
【问题讨论】:
-
在多次运行每个设置并对结果取平均值后,您是否会遇到这种情况?
-
旁白:
open("C:\output.txt", 'w')不应该是open("C:\\output.txt", 'w')吗? -
@David 结果相当一致。这适用于范围 (0,10) (0,100) (0,10000)
-
你的代码如何处理相等的元素?也许
elem1 < elem2比elem1 == elem2效果更好。 -
@Mikel 有趣的是,单个 \ 在代码中可以正常工作。我来自 Java 背景,所以转义序列对我来说仍然很新。
标签: python algorithm performance sorting quicksort