【问题标题】:How to implement quick sort on python?如何在python上实现快速排序?
【发布时间】:2020-04-13 16:01:29
【问题描述】:

也许我是下一个询问如何在 python 上正确发布快速排序的人。但是通过阅读教科书《基本算法:计算机算法的实用方法》中的伪代码,了解我是否正确编写了这个算法对我来说很重要。

当我运行代码时,我收到了这条消息。 RecursionError:比较中超出了最大递归深度

import random

def quickSort(arr, start, end):
    if start >= end:  # if len(arr) < 2
        return arr
    else:
        divideIndex = partition(arr, start, end)
        quickSort(arr, start, divideIndex - 1)
        quickSort(arr, divideIndex, end)

def partition(arr, head, tail):
    left = head
    right = tail
    pivot = arr[(head + tail) // 2]  # mid

    while right >= left:
        # looking through the array from the left
        while arr[left] <= pivot:
            left = left + 1
        # looking through the array from the right
        while arr[right] > pivot:
            right = right - 1
        # found a couple of elements that can be exchanged.
        if left <= right:
            swap(arr[right], arr[left])
            # move the left and right wall
            left = left + 1
            right = right - 1
    # return one elements if not found a couple
    return left

def swap(arr1, arr2):
    temp = arr1
    arr1 = arr2
    arr2 = temp

# Generator random variables
deck = list(range(50))
random.shuffle(deck)


start = 0
end = len(deck) - 1
print(quickSort(deck, start, end))

【问题讨论】:

  • Python 不支持尾递归优化,因此调用堆栈的长度会随着数组大小的增加而增长,因此您需要在快速排序函数中添加 while + 将 startend 放入变量而不是函数的参数
  • 您的交换功能没有按预期工作。它根本不影响数组

标签: python-3.x quicksort


【解决方案1】:

试试这个:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 2014-03-06
    • 2019-11-20
    相关资源
    最近更新 更多