简体   繁体   English

QuickSort实现可以对列表进行排序不会更新列表

[英]QuickSort implementation to sort list in place doesn't update the list

I made an implementation of the quicksort algortihm in python3.6 using recursion. 我使用递归在python3.6中实现了快速排序算法。 It sorts the list in place in increasing order. 它将列表按升序排序。 The problem however is that the list elements order do not change in the code and after the code is done running 但是,问题在于列表元素的顺序在代码中以及在代码运行完后不会更改

If you remove the base case for the recursion and let it fail on maximum recursion depth reached and put print statements in the partition method you can see it changing the elements in the list 如果删除递归的基本情况,并在达到最大递归深度时让它失败,并将print语句放在partition方法中,则可以看到它更改了列表中的元素

def partition(arr, start, end):
    pivot = arr[end]
    ix = start
    for i in range(start, end):
        print("i = ", i)
        if arr[i] <= pivot:
            arr[i], arr[ix] = arr[ix], arr[i]
            ix += 1
    arr[ix], arr[end] = arr[end], arr[ix]
    return ix

def quick_sort(arr, start, end):
    if start < end: return arr
    ix = partition(arr, start, end)
    quick_sort(arr, start, ix-1)
    quick_sort(arr, ix+1, end)

arr = [2,4,7,8,9,1,3,5,6,12,32]

print("before", arr)
print("output", quick_sort(arr, 0, len(ans)-1))
print("after", arr)

OUTPUT 
before [2, 4, 7, 8, 9, 1, 3, 5, 6, 12, 32]
output [2, 4, 7, 8, 9, 1, 3, 5, 6, 12, 32]
after [2, 4, 7, 8, 9, 1, 3, 5, 6, 12, 32]

Here: 这里:

if start < end: return arr

The logic is reversed. 逻辑相反。 It should be 它应该是

if start > end: return arr

However, because your function operates in-place, it shouldn't return anything, so it's best to make it 但是,由于您的函数在原地运行,因此不应返回任何内容,因此最好使其返回

if start > end: return

You will see that quick_sort(arr, 0, len(ans)-1) will return None , but after the function call, arr will be sorted. 您将看到quick_sort(arr, 0, len(ans)-1)将返回None ,但是在函数调用之后,将对arr进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM