冒泡排序
def bubbleSort(arr):
for i in range(len(arr)-1):
for j in range(len(arr)-1):
if arr[j]>arr[j+1]:
arr[j],arr[j+1]=arr[j+1],arr[j]
return arr
简单选择排序
def selectionSort(arr):
for i in range(len(arr)-1):
min_index=i #记录最小数的索引
for j in range(i+1,len(arr)):
if arr[j]<arr[min_index]:
min_index=j
if i!=min_index:
arr[i],arr[min_index]=arr[min_index],arr[i]
return arr
快速排序
def quickSort(arr):
def partition(arr,left,right):
key=left
while left<right:
while left<right and arr[right]>=arr[key]:
right-=1
while left<right and arr[left]<=arr[key]:
left+=1
arr[left],arr[right]=arr[right],arr[left]
arr[left],arr[key]=arr[key],arr[left]
return left
def quicksort(arr,left,right):
if left>=right:return
mid=partition(arr,left,right)
quicksort(arr,left,mid-1)
quicksort(arr,mid+1,right)
n=len(arr)
if n<=1:
return arr
quicksort(arr,0,n-1)
return arr
if __name__=='__main__':
print(quickSort([1,9,3,2,6,4,87,5,0]))
标签:arr,right,Python,range,len,算法,排序,def,left
From: https://blog.51cto.com/u_15944471/6066958