文章目录
一,插入排序(Insertion-Sort)
1,直接插入排序
视频素材 - bilibili
工作原理
代码实现
def Insertion_Sort(a):
for i in range(len(a)):
key = a[i]
j = i - 1
while i > 0 and a[i - 1] > key:
a[i] = a[i - 1]
i -= 1
a[i] = key
return a
a = [2, 3, 5, 2, 1, 9, 7, 5, 2]
b = Insertion_Sort(a)
print(b)
>>>[1, 2, 2, 2, 3, 5, 5, 7, 9]
算法分析
时间复杂度为
最佳的情况:已经由小到大排好序
第5行 则只会被执行 n-1 次
第6,7行 则不会被执行
最差情况:列表为逆序
第5行 对任何一个 a[i] 进行排序时 都会被执行 i 次(共有n个a[i])
第6,7行 随同 行5,每一次排序会被执行 i-1 次(进行n次排序)
时间复杂度【最好情况–最坏情况–平均情况】–空间复杂度–稳定性
2,折半插入排序
视频素材 - bilibili
工作原理
代码实现
def BinaryInsertSort(list):
for i in range(2, len(list)):
list[0] = list[i]
low = 1
high = i - 1
while low <= high:
m = int((low + high) / 2) # 折半
if list[0] < list[m]: # 插入点在低半区
high = m - 1
else: # 插入点在高半区
low = m + 1
j = i - 1 # 记录后移
while j >= high + 1:
list[j + 1] = list[j]
j -= 1
list[high + 1] = list[0]
其中[0]=-1这一位置是暂存单元,不会参与排序
a = [-1, 2, 3, 5, 2, 1, 9, 7, 5, 2]
BinaryInsertSort(a)
print(a)
>>>[2, 1, 2, 2, 2, 3, 5, 5, 7, 9]
算法分析
与直接插入排序法相比:
折半插入减少了比较次数,但没有减少移动次数(平均性能更优)
当数据量 n 较大时,且数据越乱,越适合用折半排序
而在最佳情况下时,直接排序(只用比较一次)反而优于折半排序
3,希尔排序
视频素材 - bilibili
基本思想
希尔排序的算法特点:
- 缩小增量
- 多遍插入排序
- 一次移动,移动位置较大,跳跃式的接近排序后的最终位置
- 最后一次只需要少量移动
- 增量序列必须是递减的,最后一个必须是 “1”
- 增量序列应该是互质的(互质是公约数只有1的两个整数,叫做互质整数。)
排序思路:
增量 5 > 3 > 1
代码实现
def shell_Sort(alist):
sublistcount = len(alist) // 2 # 除2后取不超过结果的最大整数
while sublistcount > 0:
for startposition in range(sublistcount):
InsertionSort(alist, startposition, sublistcount)
print("增量:", sublistcount,
"此时列表:", alist)
sublistcount = sublistcount // 2 # 增量每次减小一半
def InsertionSort(alist, start, gap):
"""
:param alist: 需要排序的列的表
:param start: 开始位置
:param gap: 增量
:return: 排序后列表
"""
for i in range(start + gap, len(alist), gap):
currentvalue = alist[i]
position = i
while position >= gap and alist[position - gap] > currentvalue:
alist[position] = alist[position - gap]
position = position - gap
alist[position] = currentvalue