冒泡/选择/插入排序简析

排序
冒泡排序

列表每两个相邻的数, 如果前面比后面大则交换两个数.

每遍历一遍, 无序区内最大的数放入了有序区. 无序区数量-1, 有序区数量+1

优化: 每趟的区域数量只改变1, 假如中途恰好全部排序, 就仍然必须走完剩余趟数. 因此设置flag, 如果发生空趟则立刻终止.

def bubble_sort(lists):
    tik = len(lists) - 1  # 无序区最后一位索引

    while tik > 0:
        temp = 0  # 移动指针
        flag = False  # 一趟是否发生排序
        
        while temp < tik:
            if lists[temp] > lists[temp+1]:
                lists[temp], lists[temp+1] = lists[temp+1], lists[temp]
                flag = True
            temp = temp + 1
            
        if flag is None:  # 一趟没有排序则直接返回列表
            return lists
                
        tik = tik - 1
    return lists

规模为列表长度n:

T(n) = n + n-1 + n-2 + …+ 1 = (n2+n)/2

因此时间复杂度O( n2)

选择排序

每次遍历选出最小的放入新列表. 遍历n次.

def select_search(lists):
    new_lists = []

    while lists:
        temp = 0
        i = 0
        while i < len(lists): # 找出最小元素
            if lists[temp] <= lists[i]:
                pass
            else:
                temp = i
            i = i + 1
		# 上述操作==min(lists)
        new_lists.append(lists[temp]) # 放入新列表
        del lists[temp] # 删除该元素
    return new_lists

优化: 不创建新列表, 而是将最小值与列表无序区第一个交换,

def select_search(lists):
    min_loc = 0  # 无序区第一位

    while min_loc < len(lists):
        temp = min_loc
        i = min_loc
        
        while i < len(lists):
            if lists[temp] <= lists[i]:
                pass
            else:
                temp = i
            i = i + 1
        lists[min_loc], lists[temp] = lists[temp], lists[min_loc]
        
        min_loc = min_loc + 1
    return lists

显然时间复杂度与冒泡排序一样

插入排序:

每次从无序区拿一个元素, 放入有序区的正确位置:

def insert_search(lists):
    for min_loc in range(1, len(lists)):
        # 默认第一位为有序区, 遍历无序区
        temp = lists[min_loc]  # 一个额外空间存储抽的数字
        
        for i in range(min_loc):
            # 遍历有序区
            if temp > lists[i]:
                pass
            else:  # 插入
                lists[i+1:min_loc+1] = lists[i:min_loc]
                lists[i] = temp
                break

    return lists

T(n) = 1+2+3+4+…+n-1 = n2-n

因此O(n2)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值