选择排序

核心思想:给定一个列表或者数组等类似的数据结构,其下标L=0 to N-1
1.Find the position X of the smallest item in the range of [L…N−1],
发现下标范围【L N-1】中最小的位置X
2.Swap X-th item with the L-th item,
交换X位置与L位置的值
3.Increase the lower-bound L by 1 and repeat Step 1 until L = N-2.
增加下限L+1至L=N-2

方法1def find_smallest(arr):
    smallest = arr[0]
    smallest_index = 0
    for i in range(len(arr)):
        if smallest >= arr[i]:
            smallest = arr[i]
            smallest_index = i
    return smallest_index


def selection_sort(arr):
    new_arr = []
    for i in range(len(arr)):
        smallest = find_smallest(arr)
        new_arr.append(arr.pop(smallest))
    return new_arr

a = [1, 4, 3, 7]
print(selection_sort(a))

方法2def selection_sort2(list2):
    for i in range(0, len(list2)-1):
        min_ = i
        for j in range(i + 1, len(list2)):
            if list2[j] < list2[min_]:
                min_ = j
                list2[i], list2[min_] = list2[min_], list2[i]  # swap
    return list2

a = [1, 4, 3, 7]
print(selection_sort2(a))


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值