Python全栈[第十二篇]:简单选择排序/二元选择排序

  • 选择排序/核心算法
    • 每一趟两两比较大小,找出极值(极大值或极小值)并放置到有序区的位置(index交换)
simple_list = [[2, 9, 4, 10, 6, 8, 7], [7, 8, 5, 9, 3], [7, 8, 5, 9, 3, 4, 10, 6, 8, 7]]
choices = simple_list[0]
len_choices = len(choices)
for i in range(len_choices - 1):
    maxindex = i  # 假设i就是极大值
    for j in range(i + 1, len_choices):
        if choices[maxindex] < choices[j]:
            maxindex = j
    if maxindex != i:  # 最大值就是自己本身,不需要交换
        choices[i], choices[maxindex] = choices[maxindex], choices[i]
print(choices)

在这里插入图片描述

[10, 9, 8, 7, 6, 4, 2]
  • 二元选择排序
    • 一次固定极大值和极小值
simple_list = [[2, 9, 4, 10, 6, 8, 7], [7, 8, 5, 9, 3], [7, 8, 5, 9, 3, 4, 10, 6, 8, 7]]
choices = simple_list[0]
len_choices = len(choices)
for i in range(len_choices//2):  # 一次固定两个值,减半
    maxindex = i  # 假设最大值index
    minindex = -i-1  # 假设最小index 负索引
    minorigin = minindex  # 记住 -i-1
    for j in range(i + 1, len_choices-i):  # 每次左边 +1 向右边走, 右边也需要 +1 向左走
        if choices[maxindex] < choices[j]:
            maxindex = j
        if choices[minindex] > choices[-j-1]:  # 负索引向左比较
            minindex = -j-1
    if maxindex != i:  # 最大值就是自己本身,不需要交换
        choices[i], choices[maxindex] = choices[maxindex], choices[i]
    # if minindex != -i-1:   # -i-1  多次计算,给 它一个赋值减少计算
    #     choices[-i-1],choices[minindex] = choices[minindex],choices[-i-1]
    if minindex != minorigin:   # -i-1  多次计算,给 它一个赋值减少计算
        choices[minorigin], choices[minindex] = choices[minindex], choices[minorigin]
print(choices)
  • 注:
    两次交换最大值交换后最小值索引没有跟着数字一起变换,逻辑错误出现BUG

在这里插入图片描述

simple_list = [[2, 9, 4, 10, 6, 8, 7], [7, 8, 5, 9, 3], [7, 8, 5, 9, 3, 4, 10, 6, 8, 7]]
choices = simple_list[2]
len_choices = len(choices)
for i in range(len_choices//2):  # 一次固定两个值,减半
    maxindex = i  # 假设最大值index
    minindex = -i-1  # 假设最小index 负索引
    minorigin = minindex
    for j in range(i + 1, len_choices-i):  # 每次左边 +1 向右边走, 右边也需要 +1 向左走
        if choices[maxindex] < choices[j]:
            maxindex = j
        if choices[minindex] > choices[-j-1]:  # 负索引向左比较
            minindex = -j-1
    if choices[minindex] == choices[maxindex]:
        break   # 如果极大值和极小值相等,那么剩下的数据肯定是一样重复的,不需要再次比较大小
    if maxindex != i:  # 最大值就是自己本身,不需要交换
        choices[i], choices[maxindex] = choices[maxindex], choices[i]
        if i == minindex or i == len_choices + minindex:  # 当最大值的索引等于交换索引i时需要变更minindex的值
            minindex = maxindex - len_choices
    if minindex != minorigin:
        choices[minorigin], choices[minindex] = choices[minindex], choices[minorigin]
print(choices)
[10, 9, 8, 8, 7, 7, 6, 5, 4, 3]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值