繁体   English   中英

Python-就地快速排序程序

[英]Python- Quicksort program in-place

我这里有一个快速排序程序,但结果似乎有问题。 我认为在引用某些值时,在下面突出显示的区域中一定存在一些问题。 有什么建议?

#where l represents low, h represents high
def quick(arr,l,h):
    #is this the correct array for quicksorting?
    if len(x[l:h]) > 1:
        #r is pivot POSITION
        r = h
        #R is pivot ELEMENT
        R = arr[r]
        i = l-1
        for a in range(l,r+1):  
            if arr[a] <= arr[r]:
                i+=1
                arr[i], arr[a] = arr[a], arr[i]
        #should I take these values? Note that I have repeated elements below, which is what I want to deal with
        quick(arr,l,arr.index(R)-1)
        quick(arr,arr.index(R)+arr.count(R),h)

x = [6,4,2,1,7,8,5,3]

quick(x,0,len(x)-1)

print(x)
 #should I take these values? Note that I have repeated elements below, which is what I want to deal with quick(arr,l,arr.index(R)-1) quick(arr,arr.index(R)+arr.count(R),h)

您似乎假设等于枢轴元素的值已经是连续的。 对于您当前的实现,这种假设可能是错误的。 例如通过在递归之前输出完整列表来测试它。

要使假设成立,请将其划分为三个而不是两个组,如Wikipedia 中所述

请检查这个。 我想你找到了答案。

def partition(array, begin, end):
    pivot = begin
    for i in xrange(begin+1, end+1):
        if array[i] <= array[begin]:
            pivot += 1
            array[i], array[pivot] = array[pivot], array[i]
    array[pivot], array[begin] = array[begin], array[pivot]
    return pivot


def quicksort(array, begin=0, end=None):
    if end is None:
        end = len(array) - 1
    if begin >= end:
        return
    pivot = partition(array, begin, end)
    quicksort(array, begin, pivot-1)
    quicksort(array, pivot+1, end)

array = [6,4,2,1,7,8,5,3]
quicksort(array)
print (array)

暂无
暂无

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

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