bubble.py
#coding: utf-8
def bubble_sort(alist):
"""冒泡排序"""
#两两依次比较
#稳定
# 最优时间复杂度O(n)
# 最坏时间复杂度O(n^2)
n=len(alist)
for j in range(n-1):
count=0
for i in range(0,n-1-j):
if alist[i]>alist[i+1]:
alist[i],alist[i+1]=alist[i+1],alist[i]
count+=1
if count == 0:
return 0
if __name__ == "__main__":
li=[32,43,12,32,24,54,45,56,370,1,2]
print(li)
bubble_sort(li)
print(li)
insert.py
#coding: utf-8
def insert_sort(alist):
"""插入排序"""
#从后面无序组选择依次选择元素插入前面有序组
#稳定
#最优时间复杂度O(n)
#最坏时间复杂度O(n^2)
n=len(alist)
for i in range(1,n):
while i > 0:
if alist[i] < alist[i-1]:
alist[i],alist[i-1]=alist[i-1],alist[i]
i-=1
else:
break
if __name__ == "__main__":
li=[32,43,12,32,24,54,45,56,370,1,2]
print(li)
insert_sort(li)
print(li)
merge.py
# codig: utf-8
def merge_sort(alist):
"""归并排序"""
# 稳定
# 最优时间复杂度O(nlogn)
# 最坏时间复杂度O(nlogn
# 但由于产生新的列表,所以空间复杂度会更大
n = len(alist)
if n <= 1:
return alist
mid = n // 2
left_li = merge_sort(alist[:mid])
right_li = merge_sort(alist[mid:])
left_pointer, right_pointer = 0, 0
result = []
while left_pointer < len(left_li) and right_pointer < len(right_li):
if left_li[left_pointer] < right_li[right_pointer]:
result.append(left_li[left_pointer])
left_pointer += 1
else:
result.append(right_li[right_pointer])
right_pointer += 1
result += left_li[left_pointer:]
result += right_li[right_pointer:]
return result
if __name__ == "__main__":
li=[25,43,12,1,3,32,24,54,32,20,54,56,380]
print(li)
res=merge_sort(li)
print(res)
quick.py
# coding: utf-8
def quick_sort(alist, first, last):
"""快速排序,最重要"""
# 不稳定
# 最优时间复杂度O(nlogn)
# 最坏时间复杂度O(n^2)
if first >= last:
return
mid_value = alist[first]
low = first
high = last
while low < high:
while low < high and alist[high] >= mid_value:
high-=1
alist[low]=alist[high]
while low < high and alist[low] < mid_value:
low+=1
alist[high]=alist[low]
alist[low]=mid_value
quick_sort(alist,first,low-1)
quick_sort(alist,low+1,last)
if __name__ == "__main__":
li=[25,43,12,1,3,32,24,54,32,20,54,56,380]
print(li)
quick_sort(li,0,len(li)-1)
print(li)
select.py
#coding: utf-8
#####先写第一次######
def select_sort(alist):
"""选择排序"""
#每次选择最小值
#不稳定
# 最优时间复杂度O(n^2)
# 最坏时间复杂度O(n^2)
n=len(alist)
for j in range(n):
min=j
for i in range(j+1,n):
if alist[i] < alist[min]:
min=i
alist[j],alist[min]=alist[min],alist[j]
if __name__ == "__main__":
li=[32,43,12,32,24,54,45,56,370,1,2]
print(li)
select_sort(li)
print(li)
shell.py
#coding: utf-8
def shell_sort(alist):
"""希尔排序"""
# 不稳定
# 最优时间复杂度:依gap而定
# 最坏时间复杂度O(n^2)
n=len(alist)
gap=n//2
while gap >= 1:
for j in range(gap,n):
i=j
for i in range(n):
while i > 0:
if alist[i] < alist[i-gap]:
alist[i],alist[i-gap]=alist[i-gap],alist[i]
i-=gap
else:
break
gap//=2
if __name__ == "__main__":
li=[32,43,12,32,24,54,45,56,370,1,2,365,65,666,76,90,9]
print(li)
shell_sort(li)
print(li)