博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Quick Sort with Python

Posted on 2011-10-09 15:30  Billowen  阅读(228)  评论(0)    收藏  举报

最近在看《算法导论》,同时又在学习Python,所以想到用PYTHON实现看过的算法,来练手。

PYTHON帮忙看看有没有需要改进的写法。

刚接触PYTHON,可能代码写得不够优美。

def quick_sort(A, left, right):
if right > left:
# choose the left item as pivot
pivotIndex = left
pivotNewIndex = partition(A, left, right, pivotIndex)
quick_sort(A, left, pivotNewIndex-1)
quick_sort(A, pivotNewIndex+1, right)

def partition(A, left, right, pivotIndex):
A[pivotIndex], A[right] = A[right], A[pivotIndex]
pivotValue = A[right]
storeIndex = left
for j in range(left, right):
if A[j] <= pivotValue:
A[storeIndex], A[j] = A[j], A[storeIndex]
storeIndex += 1
A[storeIndex], A[right] = A[right], A[storeIndex]
return storeIndex