Python 算法之冒泡排序

Posted evescn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 算法之冒泡排序相关的知识,希望对你有一定的参考价值。

Python 算法之冒泡排序

Python 算法之冒泡排序

冒泡排序

冒泡排序算法的原理如下:(从后往前)

  • 1、比较相邻的元素。如果第一个比第二个大,就交换他们两个。
  • 2、对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
  • 3、针对所有的元素重复以上的步骤,除了最后一个。
  • 4、持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。 

对下列数据进行排序

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

代码

#/usr/bin/eve python
 
data = [10,4,33,21,54,3,8,11,5,22,2,1,17,13,6]
 
l = len(data)
 
for i in range(l):
    for j in range(l-1-i):
        if data[j] > data[j+1]:
            tmp = data[j]
            data[j] = data[j+1]
            data[j+1] = tmp
    print(data)
print(data)

输出结果

[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]
[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]  

生成一个4*4的2维数组并将其顺时针旋转90度

代码

#!/usr/bin/env python
 
def xz(sz, n):
    for i in range(n):
        for j in range(i, n):
            if i == j:
                continue
            else:
                sz[i][j], sz[j][i] = sz[j][i], sz[i][j]
 
    return sz
 
data = [[col for col in range(4)] for row in range(4)]
for i in data:
    print(i)
print("----------------------------")
 
b = xz(data, 4)
for i in b:
    print(i)

输出结果

[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3]
----------------------------
[0, 0, 0, 0]
[1, 1, 1, 1]
[2, 2, 2, 2]
[3, 3, 3, 3]

以上是关于Python 算法之冒泡排序的主要内容,如果未能解决你的问题,请参考以下文章

Python之冒泡排序算法

Python十大经典算法之冒泡排序

11.python排序算法之冒泡排序简单选择排序,二元选择排序直接插入排序

排序算法冒泡选择排序的Python实现及算法优化详解

排序算法之冒泡排序

冒泡排序之python