冒泡排序:
def bubble_sort(alist):
for i in range(len(alist)-1,0,-1):
for j in range(i):
if alist[j]>alist[j+1]:
alist[j],alist[j+1] = alist[j+1],alist[j]
li = [54,26,93,17,77,31,44,55,20]
bubble_sort(li)
print(li)
结果:
[93, 77, 55, 54, 44, 31, 26, 20, 17]
选择排序:
def select_sort(alist):
n=len(alist)
for i in range(n-1):
min_index = i
for j in range(i+1,n):
if alist[j] < alist[min_index]:
min_index = j
if min_index != i:
alist[i],alist[min_index] = alist[min_index],alist[i]
li = [54,26,93,17,77,31,44,55,20]
select_sort(li)
print(li)
结果:
[17, 20, 26, 31, 44, 54, 55, 77, 93]
插入排序:
def insert_sort(alist):
for i in range(1,len(alist)):
for j in range(i,0,-1):
if alist[j]<alist[j-1]:
alist[j],alist[j-1] = alist[j-1],alist[j]
li = [54,26,93,17,77,31,44,55,20]
insert_sort(li)
print(li)
结果:
[17, 20, 26, 31, 44, 54, 55, 77, 93]
希尔排序:
def shell_sort(arry):
n = len(arry)
gap = n//2
while gap>0:
for i in range(gap,n):
j = i
while(j>=gap and arry[j-gap] > arry[j]):
arry[j-gap],arry[j] = arry[j],arry[j-gap]
j -= gap
gap = gap//2
alist = [54,26,93,17,77,31,44,55,20,12]
shell_sort(alist)
print(alist)
[12, 17, 20, 26, 31, 44, 54, 55, 77, 93]
快速排序:
def quick_sort2(arry,start,end):
if start>=end:
return
piv = arry[start]
left = start
right = end
while left<right:
while left<right and arry[right]>=piv:
right -=1
arry[left] = arry[right]
while left<right and arry[left]<piv:
left += 1
arry[right] = arry[left]
arry[right] = piv
quick_sort2(arry,start,right-1)
quick_sort2(arry,right+1,end)
li=[54,26,93,17,77,31,44,55,20]
quick_sort2(li,0,len(li)-1)
print(li)
[17, 20, 26, 31, 44, 54, 55, 77, 93]
归并排序:
def merge_sort(arry):
if len(arry)<=1:
return arry
mid = len(arry)//2
# 左侧递归调用归并排序到有序
left_arry = merge_sort(arry[:mid])
# 右侧递归调用归并排序到有序
right_arry = merge_sort(arry[mid:])
l , r = 0,0
result =[]
while l<len(left_arry) and r<len(right_arry):
if left_arry[l]<right_arry[r]:
result.append(left_arry[l])
l+=1
else:
result.append(right_arry[r])
r += 1
result = result + left_arry[l:]
result = result + right_arry[r:]
return result
alist = [54,26,93,17,77,31,44,55,20,12]
new = merge_sort(alist)
print(new)
[12, 17, 20, 26, 31, 44, 54, 55, 77, 93]
|