Python- Quicksort程序就地 [英] Python- Quicksort program in-place

查看:97
本文介绍了Python- Quicksort程序就地的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a quicksort program here, but there seems to be a problem with the result. I think there must have been some issue in the areas highlighted below when referencing some values. Any suggestions?

#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)

推荐答案

请选中此项.我想您找到了答案.

Please check this. I think you find your answer.

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)

这篇关于Python- Quicksort程序就地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆