简体   繁体   中英

Python- Quicksort program in-place

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

You seem to be assuming that the values equal to the pivot element are already consecutive. This assumption is probably wrong for your current implementation. Test it eg by outputting the full list before recursing.

To make the assumption true, partition into three instead of just two groups, as described at Wikipedia .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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