在列表> = 7000上使用quicksort会导致堆栈溢出

时间:2019-05-27 11:33:22

标签: python stack-overflow quicksort

我正在尝试对越来越大的数据集测试多种排序算法的计算时间。 Quicksort达到7000时出现内存错误。

我已将递归限制设置为10 ** 6,以便在使用timsort时克服最大递归深度

from random import randint
import time
import math
start = 1000
finish = 10000
inc = 1000
import  sys
sys.setrecursionlimit(10**6)
def generateNew(z):
    listt = []
    for o in range(z):
        listt.append(randint(0, z))
    return listt

...


def partition(arr,low,high): 
    i = ( low-1 )
    pivot = arr[high]

    for j in range(low , high): 
        if   arr[j] <= pivot: 
            i = i+1 
            arr[i],arr[j] = arr[j],arr[i] 

    arr[i+1],arr[high] = arr[high],arr[i+1] 
    return ( i+1 ) 
def quickSort(arr,low,high): 
    if low < high: 
        pi = partition(arr,low,high) 
        quickSort(arr, low, pi-1) 
        quickSort(arr, pi+1, high) 

def quickSortTimer(unsorted):
    start = time.time()
    array = unsorted
    quickSort(array,0,len(array)-1) 

    end = time.time()
    print("Quick Sort: "+str(end - start))


...


def runAll():


    for h in range(start, finish+1, inc):
        print("\n\nCurrent: "+str(h))
        unsorted = generateNew(h)
        oddEvenSortTimer(unsorted)
        #stoogeSortTimer(unsorted)
        gnomeSortTimer(unsorted)
        #bogoSortTimer(unsorted)
        binaryInserionSortTimer(unsorted)
        pancakeSortTimer(unsorted)
        bitonicSortTimer(unsorted)
        cocktailSortTimer(unsorted)
        cycleSortTimer(unsorted)
        pigeonholeSortTimer(unsorted)
        combSortTimer(unsorted)
        timSortTimer(unsorted)
        shellSortTimer(unsorted)
        bucketSortTimer(unsorted)
        radixSortTimer(unsorted)
        heapSortTimer(unsorted)
        quickSortTimer(unsorted)
        mergeSortTimer(unsorted)
        selectionSortTimer(unsorted)
        insertionSortTimer(unsorted)
        bubbleSortTimer(unsorted)

我希望程序继续运行,但我收到错误消息:MemoryError:堆栈溢出。该问题被标记为与另一个问题的重复,解释了如何增加递归深度,但这是另一个错误。我想保持递归深度,但要避免堆栈溢出错误。

1 个答案:

答案 0 :(得分:1)

为避免堆栈溢出,请在较小(或相等)的部分上使用递归,然后迭代返回以处理较大的部分。

def quicksort(a, lo, hi):
    while(hi - lo > 0):
        pivot = a[hi]
        i = lo
        for j in xrange(lo, hi):
            if a[j] <= pivot:
                a[i],a[j] = a[j],a[i]
                i += 1
        a[i],a[hi] = a[hi],a[i]
        if(i - lo <= hi - i):
            quicksort(a, lo, i-1)
            lo = i+1
        else:
            quicksort(a, i+1, hi)
            hi = i-1