演算法 - 排序(最全讲解+Python代码实现?)

一,插入排序(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

                
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值