在QuickSort中展平递归

时间:2014-12-17 01:14:01

标签: python recursion quicksort

所以我试图在Python 2.7中实现QuickSort,并且我已经成功地使用了递归函数,但是当我调用quicksort(range(1000)[:: - 1])时,可以理解这会让我感到沮丧。也就是说它最大限度地提高了Python中允许的递归深度。

所以现在我想"压扁"这个函数,也就是说,使用尽可能少的(或没有)递归调用。我一直试图通过一个没有返回列表的分区函数来实现这个功能,但只是在将所有内容排序到左右之后才返回数据库的位置。我已经写过并测试过它,它似乎完美无缺。但是,如果有人对此感兴趣,则代码如下。

现在的诀窍似乎是让这个东西反复分区,直到整个列表被排序,并且我很难看到如何让这个部分发生。我有一个想法是创建一个有序的索引列表,这些索引是用于数据透视的所有索引。然后我可以运行一个while循环,当索引列表与range(n)相同时会中断。我不确定这个想法有多聪明或优雅,因为我正在制作与输入列表长度相同的第二个列表 - 看起来有点像一个可以避免的记忆力。另一方面,你似乎需要一种方法来跟踪你已经排序的列表中的哪些段,为此我只能想到递归或这个列表的想法。

所以问题是,列表的想法是好还是坏,如果不好,什么是更好的主意?

def partition(x, start, end, pivotIndex):
    '''
    x is a list, start to end is the portion of the list to sort, and 
    pivotIndex is the index at which pull a value and sort everything above
    and below this.
    '''
    low = start # Low will track the lower bound of the position in the list
                # where "small" elements get switched into.  It starts at 
                # start.
    high = end-1
    p = x[pivotIndex] # Pivot value
    x[pivotIndex] = x[end] # We basically move the pivot entry out of the way
                           # and we'll put it back in at the end.
    while True:
        while low <= high and x[low] < p: # We cycle up the bottom of the list
                          # until we've looked at everything or until we hit
                          # a pice that's out of place.
            low += 1
        while low <= high and x[high] >= p: # And do likewise from the top of 
                         # the list.
            high -= 1
        if low > high: # If we've covered the whole list, the partition is 
                       # done.  Otherwise, there must be pieces out of place
                       # so swap them.
            break
        x[low], x[high] = x[high], x[low]
    x[end] = x[low] # The value at end stores a duplicate of some value,
                    # since we copied it in, so now we want to over-ride that.
                    # We choose to put the element now at low there, and put
                    # since the pivot value was taken out of the list, we now
                    # put it in the low position.
    x[low] = p
    return low

0 个答案:

没有答案