标签:算法设计 ret org html 快速排序 pytho sort range course
??归并排序和快速排序都是使用分而治之的思维.归并排序侧重点是最终结果的合并.快速排序的重点则是放在了子问题的分解上面.
def quick_sort(arr):
len_arr = len(arr)
if len_arr<2:
return arr
middle_value = arr[len_arr//2]
arr.remove(middle_value)
left,right = [],[]
for item in arr:
if item < middle_value:
left.append(item)
else:
right.append(item)
print(left,right)
return quick_sort(left) + [middle_value] + quick_sort(right)
arr = [6,15,8,7]
#print(quick_sort(arr))
def quick_sort_for_book(arr,left,right):
if left<right:
q = partition(arr,left,right)
# 使用了两次递归比较难以理解.
quick_sort_for_book(arr,left,q-1)
quick_sort_for_book(arr,q+1,right)
def partition(arr,left,right): # 数组划分
x = arr[right]
i = left -1
for j in range(left,right):
if arr[j] <=x:
i+=1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[right] = arr[right],arr[i+1]
return i + 1
arr1 = [8,6,15,14,13]
quick_sort_for_book(arr1,0,len(arr1)-1)
print(arr1)
标签:算法设计 ret org html 快速排序 pytho sort range course
原文地址:https://www.cnblogs.com/gtscool/p/12496447.html