码迷,mamicode.com
首页 > 编程语言 > 详细

冒泡排序

时间:2017-06-07 19:45:13      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:循环   als   break   false   not   []   code   class   app   

  1. """
  2. 冒泡排序
  3. 把无序的数组按照从小到大的顺序进行排序
  4. 时间复杂度O(n2)
  5. """
  6. # 创建一个不规则数组
  7. import random
  8. arry = []
  9. # 循环20次
  10. for i in range(20):
  11. # 每次生成一个随机数
  12. arry.append(random.randrange(1000))
  13. # 冒泡排序
  14. def bubble_sort1(data):
  15. for i in range(len(data) - 1):
  16. for j in range(len(data) - 1 - i):
  17. if data[j] > data[j + 1]:
  18. data[j], data[j + 1] = data[j + 1], data[j]
  19. # 冒泡排序 如果没有交换那么排序已经完成。
  20. def bubble_sort2(data):
  21. for i in range(len(data) - 1):
  22. exchange = False
  23. for j in range(len(data) - 1 - i):
  24. if data[j] > data[j + 1]:
  25. data[j], data[j + 1] = data[j + 1], data[j]
  26. exchange = True
  27. if not exchange:
  28. break
  29. # 调用冒泡排序
  30. bubble_sort1(arry)
  31. print(arry)
  32. bubble_sort2(arry)
  33. print(arry)

冒泡排序

标签:循环   als   break   false   not   []   code   class   app   

原文地址:http://www.cnblogs.com/mjxup/p/6eb90c468aa981e0210b5ea49495b252.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!