【发布时间】:2013-11-30 09:26:06
【问题描述】:
调用的函数:(不考虑类)
def partition( pivot, lst ):
less, same, more = list(), list(), list()
for val in lst:
if val < pivot:
less.append(val)
elif val > pivot:
more.append(val)
else:
same.append(val)
return less, same, more
def medianOf3(lst):
"""
From a lst of unordered data, find and return the the median value from
the first, middle and last values.
"""
finder=[]
start=lst[0]
mid=lst[len(lst)//2]
end=lst[len(lst)-1]
finder.append(start)
finder.append(mid)
finder.append(end)
finder.sort()
pivot_val=finder[1]
return pivot_val
主要代码
def quicheSortRec(lst,limit):
"""
A non in-place, depth limited quickSort, using median-of-3 pivot.
Once the limit drops to 0, it uses heapSort instead.
"""
if limit==0:
return heapSort.heapSort(lst)
else:
pivot=qsPivotMedian3.medianOf3(lst) # here we select the first element as the pivot
less, same, more = qsPivotMedian3.partition(pivot, lst)
return quicheSortRec(less,limit-1) + same + quicheSortRec(more,limit-1)
def quicheSort(lst):
"""
The main routine called to do the sort. It should call the
recursive routine with the correct values in order to perform
the sort
"""
N=len(lst)
end= int(math.log(N,2))
if len(lst)==0:
return list()
else:
return quicheSortRec(lst,end)
所以这段代码应该获取一个列表并使用中位数为 3 的快速排序实现对其进行排序,直到它达到深度递归限制,此时函数将改为使用 heapsort。这段代码的结果是然后输入另一个程序,该程序旨在测试长度为 1,10,100,1000,10000,100000 的列表的算法。
但是,当我运行代码时,告诉我长度 1 和 10 可以正常工作,但在那之后,它会给出一个列表索引超出范围的错误
start=lst[0] 在3个函数的中位数
我不知道为什么。
【问题讨论】:
-
请给出一个具体的例子,其他人可以运行,出现错误的列表。如果你这样做了,我敢打赌你自己会发现问题 ;-)
标签: python recursion quicksort heapsort