Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quicksort - CLRS implementation in python

I am trying to implement quick sort in python. The CLRS algo version.

Here is what i have written. I think it is working fine for the most part except for the middle elements of the list.

Can someone help?

#! /usr/bin/python

#quick sort

def swap(array,i,j):
    temp = array[i]
    array[i] = array[j]
    array[j] = temp

def partition(array, start,end):
    x = array[end]
    i = start -1
    for j in xrange(start+1, end):
        if (array[j] <= x):
            i = i+1
            swap (array,i,j)
        swap(array,i+1,end)
    return i+1

def quicksort(array,p,r):
    if p<r:
        q = partition(array,p,r)
        quicksort(array,p,q-1)
        quicksort(array,q+1,r)

def main():
    unsortedArray = [2,8,7,1,3,5,6,4,9,0]
    quicksort(unsortedArray,0,len(unsortedArray)-1)
    print unsortedArray


if __name__ == '__main__':
    main()

The output should be [0,1,2,3,4,5,6,7,8,9].Instead it is printing [2, 0, 3, 4, 1, 6, 5, 7, 9, 8].

like image 453
shobhit1 Avatar asked Aug 27 '26 06:08

shobhit1


1 Answers

According to the pseudocode I found on https://users.cs.fiu.edu/~giri/teach/5407/F08/Lec7.pdf, your implementation of partition is wrong, because

swap(array,i+1,end)

should NOT be carried out in every iteration, but instead only once in the function.

I rewrote it like this:

def partition(array, start,end):
    x = array[end]
    i = start -1
    for j in xrange(start, end):
        if (array[j] <= x):
            i = i+1
            swap (array,i,j)
    swap(array,i+1, end)
    return i+1

and it works fine.

like image 62
gefei Avatar answered Aug 29 '26 20:08

gefei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!