首页 > 代码库 > python快速排序实现

python快速排序实现

方案一:容易理解的写法

 

#!/usr/bin/env python

arr = [34, 80, 10, 8, 15, 20, 16, 48, 50, 36, 18]
size = len(arr)

def partion(arr, start, end):
k = start
i = start
j = end

while j > i:
while j > i and arr[j] >= arr[k]:
j = j - 1

if j > i:
temp = arr[k]
arr[k] = arr[j]
arr[j] = temp
k = j

while j > i and arr[i] <= arr[k]:
i = i + 1

if j > i:
temp = arr[k]
arr[k] = arr[i]
arr[i] = temp
k = i

return k

def sort(arr, start, end):
if start < end:
index = partion(arr, start, end)
sort(arr, start, index)
sort(arr, index + 1, end)


print arr
sort(arr, 0, size - 1)
print arr

 

 

方案二:稍便捷的写法

#!/usr/bin/env python

arr = [34, 80, 10, 8, 15, 20, 16, 48, 50, 36, 18]
size = len(arr)

def partion(arr, start, end):
i = start
j = end
first = arr[start]

while i < j:
while i < j and arr[j] >= first:
j = j - 1
arr[i] = arr[j]

while i < j and arr[i] <= first:
i = i + 1
arr[j] = arr[i]

arr[i] = first;
return i

def sort(arr, start, end):
if start < end:
index = partion(arr, start, end)
sort(arr, start, index)
sort(arr, index + 1, end)


print arr
sort(arr, 0, size - 1)
print arr

python快速排序实现