简体   繁体   English

尝试编写快速排序的就地实现,但在返回排序数组时遇到问题

[英]Trying to write an in-place implementation of quicksort and I'm having trouble returning the sorted array

I've tried writing an in-place quicksort and I'm unable to properly return the sorted array.我尝试编写就地快速排序,但无法正确返回排序后的数组。 Based on the output from the print statement, the algorithm does appear to be sorting the array but I can't seem to return the sorted array.根据打印语句的输出,该算法似乎正在对数组进行排序,但我似乎无法返回已排序的数组。 I thought it would be sorting in place but it doesn't seem to be and I'm not sure how to correct this issue.我以为它会就地排序,但似乎不是,我不知道如何纠正这个问题。

def quicksort(array):

    if len(array) <= 1:
        return 

    pivot = len(array) - 1
    i = 0

    while i < pivot:
        if array[i] > array[pivot]:
            if i == pivot - 1:
                array[i], array[pivot] = array[pivot], array[i]
            
            array[pivot], array[pivot-1] = array[pivot-1], array[pivot]
            pivot -= 1
            array[i], array[pivot+1] = array[pivot+1], array[i]
        else:
            i += 1
        
    print(array)
    quicksort(array[:pivot])    # sorts lower
    quicksort(array[pivot:])    # sorts upper

    return array


test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(test)

The problem here is that you are slicing a list , which returns a copy and not a view .这里的问题是您正在切片一个list ,它返回一个副本而不是一个视图 Thus each of your recursive call sort a copy and not the original list.因此,您的每个递归调用都会对副本进行排序,而不是对原始列表进行排序。 I recommend you use a numpy.array as input to perform your quicksort in-place.我建议您使用numpy.array作为输入来执行就地快速排序。 Indeed (basic) slicing a numpy.array returns a view .实际上(基本)切片numpy.array返回一个 view This is the python data structure that is the closest to a canonical array.这是最接近规范数组的python数据结构。

When you make the recursive call quicksort(array[:pivot]) , you don't pass the original list to quicksort() , but instead create a new list.当您进行递归调用quicksort(array[:pivot]) ,您不会将原始列表传递给quicksort() ,而是创建一个新列表。

To avoid creating new lists, you can drop the slice syntax and instead pass array indices to your function:为避免创建新列表,您可以删除切片语法,而是将数组索引传递给您的函数:

def quicksort(array, start, length):

    if length <= 1:
        return 

    pivot = start + length - 1
    i = start

    while i < pivot:
        if array[i] > array[pivot]:
            if i == pivot - 1:
                array[i], array[pivot] = array[pivot], array[i]
            
            array[pivot], array[pivot-1] = array[pivot-1], array[pivot]
            pivot -= 1
            array[i], array[pivot+1] = array[pivot+1], array[i]
        else:
            i += 1
        
    print(array[start:start+length])
    quicksort(array, start, pivot-start)    # sorts lower
    quicksort(array, pivot, length-pivot)   # sorts upper

    return array


test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(test, 0, len(test))

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

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