在Python中快速排序并引发RecursionError

时间:2018-10-14 09:14:41

标签: python algorithm quicksort

我已经为Python中的“快速排序”编写了以下代码,但得到了 RecursionError:在比较中超出了最大递归深度 。在运行另一个具有相同逻辑的代码时,它运行良好。

下面是我写的代码:

SELECT DATE(FROM_UNIXTIME(time)) from table 

及以下是GeeksforGeeks中运行良好的代码:

def partition(Arr,start,end):
    pivot=Arr[end]
    pindex=start

    for i in range(start,end):
        if Arr[i] <= pivot:                                         

            Arr[i],Arr[pindex] = Arr[pindex],Arr[i]                   
            pindex += 1

    #print("pindex",pindex)
    Arr[pindex],Arr[end]=Arr[end],Arr[pindex]                       
    return pindex


def QuickSort(Arr,start,end):

    if(start>=end):
        return Arr


    if (start<end):
        pindex=partition(Arr,start,end)                 


        QuickSort(Arr, start, pindex-1)                 

        QuickSort(Arr, pindex-1, end)                   





Array = [10, 7, 8, 9, 1, 5]
start=0
end=len(Array)-1
sort_Arr=QuickSort(Array,start,end)
print ("Sorted array is: {}",sort_Arr)

以下是回溯-:

# This function takes last element as pivot, places
# the pivot element at its correct position in sorted
# array, and places all smaller (smaller than pivot)
# to left of pivot and all greater elements to right
# of pivot
def partition(arr,low,high):
    i = ( low-1 )         # index of smaller element
    pivot = arr[high]     # pivot

    for j in range(low , high):

        # If current element is smaller than or
        # equal to pivot
        if   arr[j] <= pivot:

            # increment index of smaller element
            i = i+1
            arr[i],arr[j] = arr[j],arr[i]

    arr[i+1],arr[high] = arr[high],arr[i+1]
    return ( i+1 )

# The main function that implements QuickSort
# arr[] --> Array to be sorted,
# low  --> Starting index,
# high  --> Ending index

# Function to do Quick sort
def quickSort(arr,low,high):
    if low < high:

        # pi is partitioning index, arr[p] is now
        # at right place
        pi = partition(arr,low,high)

        # Separately sort elements before
        # partition and after partition
        quickSort(arr, low, pi-1)
        quickSort(arr, pi+1, high)

有人可以帮我吗? 为什么我的代码无法运行? 任何建议表示赞赏。

1 个答案:

答案 0 :(得分:0)

您已选择用<footer> <div> <h3>Titre section 1</h3> <p>test</p> </div> <div> <h3>Titre section 2</h3> </div> <div> <h3>Titre section 3</h3> </div> <div> <h3>Suivez-nous</h3> <span class="Facebook"> <img src="images/Facebook.png"> 500 000 abonnés </span> <span class="twitter"> <img src="images/twitter.png"> </span> <span class="instagram"> <img src="images/instagram.png"> </span> </div> </footer> 表示数组中的范围,其中start,end是最后一个元素的索引。因此,这段代码

end

不会将数组分为两个不相交的部分- QuickSort(Arr, start, pindex-1) QuickSort(Arr, pindex-1, end) 将在这两个部分中,并且递归不会终止,因为第二部分的大小永远不会为一。

更好的约定是让pindex-1指向最后一个元素之后。 Dijkstra can explain why in more detail.