自学python笔记 冒泡法排序

冒泡法排序:

冒泡排序(Bubble Sort):重复地遍历要排序的数列,依次比较两个元素,如果他们的顺序不符就把他们交换过来。就像气泡一样,需要排序的元素通过比较、交换位置,一点一点浮到对应的位置。

个人理解的原理:

  1、比较相邻的元素。例:需要进行升序排列,如果:元素1 > 元素2   那么元素1和元素2就互换位置。(每次比较就像一个小步骤)

  2、依次对每一对相邻元素比较,从第一对到最后一对。每次完成后就把最大的元素排到当次的最后了。(这样就完成了一个大步骤)

  3、重复从头开始进行1、2的内容,但是因为前一次的比较后,都会有一个元素的位置确定,所以需要比较的元素会越来越少。

个人小节:

  升序就每次循环把最大的排每次循环的后面

  降序排列,就是每次循环把最小的排每次循环的最后面

PS:摘录自:https://www.cnblogs.com/23147-2Lemon/p/8663284.html

temp = [99, 30, 5, 8, 9, 88, 0, 96, 20, 2, 4, 87]
for n in temp:
   print("			", n)
def bubble_way(temp):
   length =len(temp)
   for i in range(0, length):
      for j in range(i +1, length):
         if temp[i] > temp[j]:
            temp[i],temp[j] = temp[j], temp[i]
   return temp
print(bubble_way(temp))

#结果
             99
             30
             5
             8
             9
             88
             0
             96
             20
             2
             4
             87
[0, 2, 4, 5, 8, 9, 20, 30, 87, 88, 96, 99]

排序过程:

temp = [99, 30, 5, 8, 9, 88, 0, 96, 20, 2, 4, 87]
for n in temp:
   print("			", n)
def bubble_way(temp):
   length =len(temp)
   for i in range(0, length):
      for j in range(i +1, length):
         if temp[i] > temp[j]:
            temp[i],temp[j] = temp[j], temp[i]
   #return temp
      print(temp)
#print(bubble_way(temp))
bubble_way(temp)

#过程
             99
             30
             5
             8
             9
             88
             0
             96
             20
             2
             4
             87
[0, 99, 30, 8, 9, 88, 5, 96, 20, 2, 4, 87]
[0, 2, 99, 30, 9, 88, 8, 96, 20, 5, 4, 87]
[0, 2, 4, 99, 30, 88, 9, 96, 20, 8, 5, 87]
[0, 2, 4, 5, 99, 88, 30, 96, 20, 9, 8, 87]
[0, 2, 4, 5, 8, 99, 88, 96, 30, 20, 9, 87]
[0, 2, 4, 5, 8, 9, 99, 96, 88, 30, 20, 87]
[0, 2, 4, 5, 8, 9, 20, 99, 96, 88, 30, 87]
[0, 2, 4, 5, 8, 9, 20, 30, 99, 96, 88, 87]
[0, 2, 4, 5, 8, 9, 20, 30, 87, 99, 96, 88]
[0, 2, 4, 5, 8, 9, 20, 30, 87, 88, 99, 96]
[0, 2, 4, 5, 8, 9, 20, 30, 87, 88, 96, 99]
[0, 2, 4, 5, 8, 9, 20, 30, 87, 88, 96, 99]

学习阶段,非原创,参考源为https://www.cnblogs.com/cookie1026/p/6116609.html,欢迎交流学习

原文地址:https://www.cnblogs.com/cn-gzb/p/9581126.html