Python中的就地QuickSort

Can*_*glu 10 python algorithm

我必须使用我选择的语言为家庭作业实现QuickSort算法,我选择了Python.

在讲座中,我们被告知QuickSort具有内存效率,因为它可以就地工作; 即,它没有用于递归的输入数组的部分的附加副本.

考虑到这一点,我尝试在Python中实现QuickSort算法,但不久之后意识到为了编写优雅的代码片段,我必须在递归时将部分数组传递给函数本身.由于Python每次执行此操作都会创建新列表,因此我尝试使用Python3(因为它支持nonlocal关键字).以下是我评论的代码.

def quicksort2(array):
# Create a local copy of array.
arr = array

    def sort(start, end):
        # Base case condition
        if not start < end:
            return

        # Make it known to the inner function that we will work on arr
        # from the outer definition
        nonlocal arr

        i = start + 1
        j = start + 1

        # Choosing the pivot as the first element of the working part
        # part of arr
        pivot = arr[start]

        # Start partitioning
        while j <= end:
            if arr[j] < pivot:
                temp = arr[i]
                arr[i] = arr[j]
                arr[j] = temp
                i += 1
            j += 1
        temp = arr[start]
        arr[start] = arr[i - 1]
        arr[i - 1] = temp
        # End partitioning

        # Finally recurse on both partitions
        sort(start + 0, i - 2)
        sort(i, end)
    sort(0, len(array) - 1)
Run Code Online (Sandbox Code Playgroud)

现在,我不确定我是做得好还是我错过了什么.我已经编写了一个更加Pythonic版本的QuickSort,但它确实无法就地工作,因为它不断返回输入数组的部分并连接它们.

我的问题是,这是用Python做的吗?我搜索了Google和SO但是没有找到真正的QuickSort就地实现,所以我认为最好问一下.

Ant*_*Ant 11

当然不是最好的方法,加上这个着名的算法将有几十个完美的实现..这是我的,很容易理解

def sub_partition(array, start, end, idx_pivot):

    'returns the position where the pivot winds up'

    if not (start <= idx_pivot <= end):
        raise ValueError('idx pivot must be between start and end')

    array[start], array[idx_pivot] = array[idx_pivot], array[start]
    pivot = array[start]
    i = start + 1
    j = start + 1

    while j <= end:
        if array[j] <= pivot:
            array[j], array[i] = array[i], array[j]
            i += 1
        j += 1

    array[start], array[i - 1] = array[i - 1], array[start]
    return i - 1

def quicksort(array, start=0, end=None):

    if end is None:
        end = len(array) - 1

    if end - start < 1:
        return

    idx_pivot = random.randint(start, end)
    i = sub_partition(array, start, end, idx_pivot)
    #print array, i, idx_pivot
    quicksort(array, start, i - 1)
    quicksort(array, i + 1, end)
Run Code Online (Sandbox Code Playgroud)

好的,首先是分区子程序的单独功能.它采用数组,感兴趣的起点和终点以及枢轴索引.这个功能应该清楚

Quicksort然后第一次在整个数组上调用partition子例程; 然后调用recursevely自己将所有内容排序到枢轴和之后的所有内容.

问你是否不明白