python 3中值为3的Quicksort实现,在满足递归深度限制后切换到heapsort

时间:2013-11-29 21:15:18

标签: python recursion quicksort heapsort

调用的函数:(不管是什么类)

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的quicksort实现进行排序,直到达到深度递归限制为止,此时函数将改为使用heapsort。此代码的结果是然后输入另一个程序,用于测试长度为1,10,100,1000,10000,100000的列表的算法。

然而,当我运行代码时,告诉我长度1和10工作正常,但在那之后,它给出了一个列表索引超出界限错误

start = lst [0]中位数为3的函数

我无法弄清楚原因。

1 个答案:

答案 0 :(得分:0)

如果没有看到您的测试数据,我们就会在这里失明。在 general

less, same, more = qsPivotMedian3.partition(pivot, lst)

本身很好,但是你永远不会检查lessmore以查看它们是否为空。即使它们是空的,也会通过以下方式传递:

    return quicheSortRec(less,limit-1) + same + quicheSortRec(more,limit-1)

quicheSortRec()不会检查它们是否为空:它无条件地调用:

pivot=qsPivotMedian3.medianOf3(lst)  

如果它传递了一个空列表,该函数将引发你看到的错误。请注意,您的quicheSort() 检查空输入。递归工作者函数也应该。

BTW,请考虑重写medianOf3()

def medianOf3(lst):
    return sorted([lst[0], lst[len(lst)//2], lst[-1]])[1]

这是一个简洁明了的案例; - )