猫史档案馆


【Python作品分享】算法与复杂性-9

用户:一起来编程吧ll一起来编程吧ll查看:0 回复:2 评论:0 创建时间:2020-06-15T19:51:34


【作品展示】

center_image

 

【作品介绍】

选择排序算法

 

【作品源代码】

List_1 = [5, 4, 3, 2, 1]
List_2 = [9, 5, 4, 3, 2, 1, 6, 2]

# 选择排序算法
def selection_sort(List):
    for j in range(len(List)):
        index = j # 最小值的索引
        for i in range(j+1,len(List)):
            if List[i] < List[index]:
                index = i
        # 方法一
        # temp = List.pop(index)
        # List.insert(j, temp)
        # 方法二
        # temp = List[j]
        # List[j] = List[index]
        # List[index] = temp
        List[j],List[index] = List[index],List[j]
            
    return List

print(selection_sort(List_1))
print(selection_sort(List_2))

# List = ['B','A','C','D']
# # 中间变量
# temp = List[2]
# List[2] = List[1]
# List[1] = temp
# print(List)

# 交换
# List[0],List[3] = List[3],List[0]
# print(List)

 

【提示】

部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:

https://python.codemao.cn


回复

上一页1 页 / 共 1下一页
宏图大志EB9j宏图大志EB9j

直接用SORT它不香么?

上代码。。。

# 数据升序
datas = [2, 5, 3, 7, 1]
datas.sort(reverse = True)
print(datas)
# 666?

# 降序?好好看看啊!
datas = [2, 5, 3, 7, 1]
datas.sort(reverse = False)
print(datas)

点赞0


评论


SKQASKQA

直接排序不行么?

datas = [3, 1, 6, 18, 13]
datas.sort(reverse = True)
print(datas)

点赞0


评论