Python 随笔排序算法

冒泡法

nums = [9,8,6,7,5,4,3,2,1]
print(nums)
length = len(nums)
for i in range(length):
    for j in range(length-i-1):
        if nums[j] > nums[j+1]:
            nums[j],nums[j+1] = nums[j+1],nums[j]
print(nums)

# 减少无用的交换次数
numlist = [
    [1,2,3,4,5,6,7,8,9]
]
nums = numlist[0]
print(nums)
length = len(nums)
count_swap = 0
count = 0
for i in range(length):
    flag = False
    for j in range(length-i-1):
        count += 1
        if nums[j] > nums[j+1]:
            nums[j],nums[j+1] = nums[j+1],nums[j]
            flag = True
            count_swap += 1
    if not flag:
        break
print(nums,count_swap,count)

简单选择排序

numlist = [
    [1,2,3,4,5,6,7,8,9],
    [9,8,7,6,5,4,3,2,1]
]
nums = numlist[1]
print(nums)
length = len(nums)
count_swap = 0
count = 0
for i in range(length):
    maxindex = i
    for j in range(i + 1,length):
        count += 1
        if nums[maxindex] < nums[j]:
            maxindex = j
    if i != maxindex:
        nums[i],nums[maxindex] = nums[maxindex],nums[i]
        count_swap += 1
print(nums,count_swap,count)

直接插入排序:

numlist = [
    [1,2,3,4,5,6,7,8,9],
    [9,8,7,6,5,4,3,2,1]
]
nums = numlist[0]
print(nums)
length = len(nums)
count_swap = 0
count = 0
for i in range(2,length):
    nums[0] = nums[i]
    j = i - 1
    count += 1
    if nums[j] > nums[0]:
        while nums[j] > nums[0]:
            nums[j+1] = nums[j]
            j -= 1
            count_swap += 1
        nums[j+1]  = nums[0]
print(nums,count_swap,count)

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

编辑于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券