python--冒泡排序

python--冒泡排序

冒泡排序的思想: 每次比较两个相邻的元素, 如果他们的顺序错误就把他们交换位置。
缺点: 冒泡排序解决了桶排序浪费空间的问题, 但是冒泡排序的效率特别低。

比如有五个数: 12, 35, 99, 18, 76, 从大到小排序, 对相邻的两位进行比较

第一趟:
第一次比较: 35, 12, 99, 18, 76
第二次比较: 35, 99, 12, 18, 76
第三次比较: 35, 99, 18, 12, 76
第四次比较: 35, 99, 18, 76, 12
经过第一趟比较后, 五个数中最小的数已经在最后面了, 接下来只比较前四个数, 依次类推
第二趟
99, 35, 76, 18, 12
第三趟
99, 76, 35, 18, 12
第四趟
99, 76, 35, 18, 12
比较完成
冒泡排序原理: 每一趟只能将一个数归位, 如果有n个数进行排序,只需将n-1个数归位, 也就是说要进行n-1趟操作(已经归位的数不用再比较)

#!/usr/bin/env python
# -*- coding:utf-8 -*-

# 冒泡排序从小到大
def bubbleSort(nums): for i in range(len(nums)-1): # 这个循环负责设置冒泡排序进行的次数 for j in range(len(nums)-i-1): # j为列表下标 if nums[j] > nums[j+1]: nums[j], nums[j+1] = nums[j+1], nums[j] return nums nums = [5,2,45,6,8,2,1] print(bubbleSort(nums))

以上代码运行结果:

[1, 2, 2, 5, 6, 8, 45]

 将一个不规则的数组按从小到大的顺序进行排序

#!/usr/bin/env python
# -*- coding:utf-8 -*-

data = [10,4,33,21,54,3,8,11,5,22,2,1,17,13,6]
print(data)
print("-----------------------------------------------------------")
for i in range(len(data) - 2):
    for j in range(len(data) - 1 - i):
        if data[j] > data[j + 1]:
            data[j], data[j + 1] = data[j + 1], data[j]
    print(data)

print("-----------------------------------------------------------")
print(data)

以上代码运行结果:

[10, 4, 33, 21, 54, 3, 8, 11, 5, 22, 2, 1, 17, 13, 6]
-----------------------------------------------------------
[4, 10, 21, 33, 3, 8, 11, 5, 22, 2, 1, 17, 13, 6, 54]
[4, 10, 21, 3, 8, 11, 5, 22, 2, 1, 17, 13, 6, 33, 54]
[4, 10, 3, 8, 11, 5, 21, 2, 1, 17, 13, 6, 22, 33, 54]
[4, 3, 8, 10, 5, 11, 2, 1, 17, 13, 6, 21, 22, 33, 54]
[3, 4, 8, 5, 10, 2, 1, 11, 13, 6, 17, 21, 22, 33, 54]
[3, 4, 5, 8, 2, 1, 10, 11, 6, 13, 17, 21, 22, 33, 54]
[3, 4, 5, 2, 1, 8, 10, 6, 11, 13, 17, 21, 22, 33, 54]
[3, 4, 2, 1, 5, 8, 6, 10, 11, 13, 17, 21, 22, 33, 54]
[3, 2, 1, 4, 5, 6, 8, 10, 11, 13, 17, 21, 22, 33, 54]
[2, 1, 3, 4, 5, 6, 8, 10, 11, 13, 17, 21, 22, 33, 54]
[1, 2, 3, 4, 5, 6, 8, 10, 11, 13, 17, 21, 22, 33, 54]
[1, 2, 3, 4, 5, 6, 8, 10, 11, 13, 17, 21, 22, 33, 54]
[1, 2, 3, 4, 5, 6, 8, 10, 11, 13, 17, 21, 22, 33, 54]
-----------------------------------------------------------
[1, 2, 3, 4, 5, 6, 8, 10, 11, 13, 17, 21, 22, 33, 54]

 

posted @ 2017-08-05 12:18  耳木东木2  阅读(156)  评论(0编辑  收藏  举报