【Python 基础】列表中的元素排序例子

假设有一个如下的列表:

我希望对其进行排序,达成排序后变成 [1,2,3,4,5,8]。
代码例子如下:

运行的结果,展示了每一次排序动作前后的变化:

x is: 0 y is: 1
mylist[x] is: 3 mylist[y] is: 5
[3, 5, 2, 1, 8, 4]
[3, 5, 2, 1, 8, 4]

x is: 0 y is: 2
mylist[x] is: 3 mylist[y] is: 2
[3, 5, 2, 1, 8, 4]
exchanged
[2, 5, 3, 1, 8, 4]

x is: 0 y is: 3
mylist[x] is: 2 mylist[y] is: 1
[2, 5, 3, 1, 8, 4]
exchanged
[1, 5, 3, 2, 8, 4]

x is: 0 y is: 4
mylist[x] is: 1 mylist[y] is: 8
[1, 5, 3, 2, 8, 4]
[1, 5, 3, 2, 8, 4]

x is: 0 y is: 5
mylist[x] is: 1 mylist[y] is: 4
[1, 5, 3, 2, 8, 4]
[1, 5, 3, 2, 8, 4]

x is: 1 y is: 2
mylist[x] is: 5 mylist[y] is: 3
[1, 5, 3, 2, 8, 4]
exchanged
[1, 3, 5, 2, 8, 4]

x is: 1 y is: 3
mylist[x] is: 3 mylist[y] is: 2
[1, 3, 5, 2, 8, 4]
exchanged
[1, 2, 5, 3, 8, 4]

x is: 1 y is: 4
mylist[x] is: 2 mylist[y] is: 8
[1, 2, 5, 3, 8, 4]
[1, 2, 5, 3, 8, 4]

x is: 1 y is: 5
mylist[x] is: 2 mylist[y] is: 4
[1, 2, 5, 3, 8, 4]
[1, 2, 5, 3, 8, 4]

x is: 2 y is: 3
mylist[x] is: 5 mylist[y] is: 3
[1, 2, 5, 3, 8, 4]
exchanged
[1, 2, 3, 5, 8, 4]

x is: 2 y is: 4
mylist[x] is: 3 mylist[y] is: 8
[1, 2, 3, 5, 8, 4]
[1, 2, 3, 5, 8, 4]

x is: 2 y is: 5
mylist[x] is: 3 mylist[y] is: 4
[1, 2, 3, 5, 8, 4]
[1, 2, 3, 5, 8, 4]

x is: 3 y is: 4
mylist[x] is: 5 mylist[y] is: 8
[1, 2, 3, 5, 8, 4]
[1, 2, 3, 5, 8, 4]

x is: 3 y is: 5
mylist[x] is: 5 mylist[y] is: 4
[1, 2, 3, 5, 8, 4]
exchanged
[1, 2, 3, 4, 8, 5]

x is: 4 y is: 5
mylist[x] is: 8 mylist[y] is: 5
[1, 2, 3, 4, 8, 5]
exchanged
[1, 2, 3, 4, 5, 8]

[1, 2, 3, 4, 5, 8] <<<< 最终的结果

Original: https://www.cnblogs.com/gaojian/p/15975361.html
Author: 健哥的数据花园
Title: 【Python 基础】列表中的元素排序例子

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/9352/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

免费咨询
免费咨询
扫码关注
扫码关注
联系站长

站长Johngo!

大数据和算法重度研究者!

持续产出大数据、算法、LeetCode干货,以及业界好资源!

2022012703491714

微信来撩,免费咨询:xiaozhu_tec

分享本页
返回顶部