某公司的面试题之一。
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]
>>>
改进版本,因为pyhon交换a,b = b,a 即可。
def patition(mylist,p,q):
key = mylist[q]
i = p-1
for j in range(p,q):
if mylist[j] <= key:
i = i+1
mylist[i],mylist[j] = mylist[j], mylist[i]
mylist[i+1],mylist[q] = mylist[q], mylist[i+1]
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
貌似简洁了些许。
吐槽:
觉得py好美,它的list传进去函数中,就是原始的list,而不是副本。
如果要看《算法导论》中的伪代码,请看下链接:http://blog.csdn.net/emaste_r/article/details/7100997