冒泡
def buble_sort(list):
'''冒泡排序'''
n = len(list)
for j in range(0,n-1):
count = 0
for i in range(0,n-1-j):
if list[i]>list[i+1]:
list[i],list[i+1] = list[i+1],list[i]
if count == 0:
return
if __name__ == '__main__':
li = [11,424,232,55,334,532,423,444,567,875]
print(li)
buble_sort(li)
print(li)
选择
def select_sort(alist):
'''选择排序'''
n = len(alist)
for j in range(0,n-1):
min_index = j
for i in range(1+j, n):
if alist[min_index] > alist[i]:
min_index = i
alist[j],alist[min_index] = alist[min_index],alist[j]
if __name__ == '__main__':
li = [44, 55, 65, 66, 33, 23, 58, 99]
print(li)
select_sort(li)
print(li)
希尔
def shell_sort(alist):
'''希尔排序'''
n = len(alist)
gap = n//2
# gap变化到0之前,插入算法执行的次数
while gap > 0:
# 插入算法与希尔排序的区别是gap的步长
for j in range(gap,n):
# j = [gap,gap+1,gap+2,gap+3,...n-1]
i = j
while i > 0:
if alist[i] < alist[i-gap]:
alist[i], alist[i-gap] = alist[i-gap], alist[i]
i -=gap
else:
break
# 缩短gap步长
gap //= 2
if __name__ == '__main__':
li = [324,424,232,55,334,532,423,444,567,875]
print(li)
shell_sort(li)
print(li)
插入
# 最坏时间复杂度 为:O(n^2) 最优时间复杂度 为:O(n) 稳定
def insert_sort(alist):
'''插入排序'''
n = len(alist)
# 从右边的无序序列中取出多少个元素执行这样的过程
for j in range(1,n):
# i 表示内层循环的起始值
i =j
# 执行从右边的无序序列中取出第一个元素,即i的位置的元素,然后将其插入到右边的有序数列的正确位置
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 = [33,445,7,6,324,536,647,1,34,5]
print(li)
insert_sort(li)
print(li)
快排
# 最优时间复杂度是:O(nlogn)
# 最坏时间复杂度是:O(nlogn)
# 稳定性:稳定
def merge_sort(alist):
'''归并排序'''
n = len(alist)
if n <= 1:
return alist
mid = n // 2
# left 采用归并排序后形成的有序的新列表
left_li = merge_sort(alist[:mid])
# left 采用归并排序后形成的有序的新列表
right_li = merge_sort(alist[mid:])
# 将2个有序列表合并成为一个新列表
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 = [324, 424, 232, 55, 334, 532, 423, 444, 567, 875]
print(li)
sort_li = merge_sort(li)
print(sort_li)
二分法
# 最优时间复杂度是:O(1)
# 最坏时间复杂度是:O(logn)
# 递归 二分法查找必须列表是排序好的
def binary_search(alist,item):
'''二分法查找'''
n = len(alist)
if n > 0:
mid = n // 2
if alist[mid] == item:
return True # 递归退出的条件
elif item < alist[mid]:
return binary_search(alist[:mid],item)
else:
return binary_search(alist[mid+1:],item)
return False
# 非递归
def binary_search_2(alist,item):
'''二分法查找'''
n = len(alist)
first = 0
last = n-1
while first <= last:
mid = (first+last)//2
if alist[mid] == item:
return True
elif item < alist[mid]:
last = mid-1
else:
first = mid+1
return False
if __name__ == '__main__':
li = [1, 6, 7, 22, 34, 53, 67, 122, 134]
print(binary_search(li,34))
print(binary_search(li,23))
print(binary_search_2(li,34))
print(binary_search_2(li,23))