python 快排


某公司的面试题之一。

RT。

 

def exchange(mylist,i,j):
    tmp = mylist[i]
    mylist[i] = mylist[j]
    mylist[j] = tmp

def patition(mylist,p,q):
    key = mylist[q]
    i = p-1
    for j in range(p,q):
        if mylist[j] <= key:
            i = i+1
            exchange(mylist,i,j)
    exchange(mylist,i+1,q)
    return i
    
def quicksort(mylist,p,q):
    if p < q:
        r = patition(mylist,p,q)
        quicksort(mylist,p,r-1)
        quicksort(mylist,r+1,q)
    
mylist = [5,8,0,2,1,9,10,3,6,7,4]
quicksort(mylist,0,len(mylist)-1)
print mylist
      

结果:

 

>>>
[0, 1, 2, 3, 4, 5, 6, 8, 7, 9, 10]
>>>

 

吐槽:

觉得py好美,它的list传进去函数中,就是原始的list,而不是副本。

 

评论关闭