Python之选择排序

代码

lst = [9,1,3,6,2,5,4,7,8,0]

nums = [0] + lst # 添加一个哨兵位
length = len(nums) # 列表长度

for i in range(2,length):    # 从2开始
    nums[0] = nums[i] # 待比较值放入哨兵位
    j = i - 1

    if nums[j] > nums[0]: # 如果哨兵小于比较数
        while nums[j] > nums[0]:
            nums[j+1] = nums[j]
            j -= 1
        nums[j+1] = nums[0]
print(nums)

解释

轮次 哨兵 1 2 3 4 5 6 7 8 9 10
原始 0 9 1 3 6 2 5 4 7 8 0
第一轮 1 1 9 3 6 2 5 4 7 8 0
第二轮 3 1 3 9 6 2 5 4 7 8 0
... ... ... ... ... ... ... ... ... ... ... ...
Last modification:June 16th, 2020 at 05:43 pm
If you think my article is useful to you, please feel free to appreciate