python中的快速排序算法

时间:2015-05-05 23:32:23

标签: python algorithm quicksort

我在python中有一个quicksort算法,我试图实现但是由于某种原因它没有正确排序,我真的很困惑为什么。我想这可能是因为随机数。我已经粘贴了以下3个功能。我对python很新,所以任何帮助都会非常感激!

import random


def swap( l, i, j ) :
 "swaps elements at indices i, j in list l"
 tmp = l[i]
 l[i] = l[j]
 l[j] = tmp

def partition( L, b, e ) :
    "Return: index of pivot"
    # move pivot element to L[0]
    swap( L, b, random.randint( b, e ))
    last = b
# Move <p to left side, marked by `last'
    for i in range( b+1, e+1 ) :
         if L[i] < L[b] :
            last += 1
            swap( L, last, i )
         swap( L, b, last ) # restore pivot
         return last

def qsort( L, b, e ) :
    # base case
    if b >= e : # nothing to do - 0 or 1 element
        return
    # partition returns index of pivot element
    piv = partition( L, b, e )
    #print piv
    # Note that the pivot is right where it belongs
    # It does not get sent out in either call
    print L
    qsort( L, b, piv-1 ) # elements in [ b, piv )
    print L
    qsort( L, piv+1, e ) # elements in ( piv, e ]
    #print L

0 个答案:

没有答案