【问题标题】:python 3 median-of-3 Quicksort implementation which switches to heapsort after a recursion depth limit is metpython 3 median-of-3 Quicksort 实现,在满足递归深度限制后切换到堆排序
【发布时间】: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


【解决方案1】:

没有看到您的测试数据,我们在这里是盲目的。在一般中,

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

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

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

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

pivot=qsPivotMedian3.medianOf3(lst)  

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

顺便说一句,考虑重写medianOf3()

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

这是一种简洁明了的情况;-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多