冒泡排序(Bubble Sort)
插入排序(Insertion Sort)
希尔排序(Shell Sort)
选择排序(Selection Sort)
快速排序(Quick Sort)
def QuickSort(arr,start,end):
if start>=end:
return
i = start
j = end
flag = arr[i]
while i < j:
#print(start,end,arr,arr[i],arr[j],i,j)
if arr[i] < flag:
i+=1
elif arr[j] > flag:
j-=1
else:
if arr[i] == arr[j]:
i+=1
else:
arr[i],arr[j] = arr[j],arr[i]
i+=1
arr[i] = flag
QuickSort(arr,start,i-1) # 这里如果写QuickSort(arr,start,i),当arr[start]==arr[i]]时,由于每次递归调用没有缩小问题规模,整个递归调用会超出最大调用栈深度
QuickSort(arr,j+1,end) # 也不能写QuickSort(arr,j,end)
nums=[3,5,1,8,3,10,3,6,2,12,62,23]
print(nums)
QuickSort(nums,0,len(nums)-1)
print(nums)
归并排序(Merge Sort)
def MergeSort(arr,start,end):
print(arr[start:end+1])
if start>=end:
return
mid = int((start+end)/2)
MergeSort(arr,start,mid)
MergeSort(arr,mid+1,end)
i = start
j = mid+1
tmp = []
## 以下为合并两个有序数组
while i<=mid and j<=end:
if arr[i]<arr[j]:
tmp.append(arr[i])
i+=1
else:
tmp.append(arr[j])
j+=1
while i<=mid:
tmp.append(arr[i])
i+=1
while j<=end:
tmp.append(arr[j])
j+=1
print('arr',arr[start:end+1])
print('tmp',tmp)
for i in range(len(tmp)):
arr[start+i] = tmp[i]
nums=[3,5,1,8,3,10,3,6,2,12,62,23]
print(nums)
MergeSort(nums,0,len(nums)-1)
print(nums)
堆排序(Heap Sort)
计数排序(Counting Sort)
桶排序(Bucket Sort)
基数排序(Radix Sort)