冒泡排序--python
1 import random 2 3 4 # 原始冒泡排序 5 def bubble_sort(nums): 6 counter = 0 7 for i in range(len(nums) - 1): # 这个循环负责设置冒泡排序的趟数 8 for j in range(len(nums) - i - 1): # 这个是每趟比较的次数,每次从0开始,底部是已有序 9 if nums[j] > nums[j+1]: 10 nums[j], nums[j+1] = nums[j+1], nums[j] 11 counter += 1 12 print('比较次数:', counter) 13 return nums 14 15 16 # 优化冒泡排序 17 def bubble_sort2(nums): 18 counter = 0 19 for i in range(len(nums) - 1): 20 ex_flag = False # 设置交换标志,如果没有进行交换,说明已排序完成,无需再进行 21 for j in range(len(nums) - 1): 22 if nums[j] > nums[j+1]: 23 nums[j], nums[j+1] = nums[j+1], nums[j] 24 counter += 1 25 ex_flag = True 26 if not ex_flag: 27 break 28 print('比较次数', counter) 29 return nums 30 31 def test_arr(count, limit): 32 arr = [] 33 for i in range(count): 34 arr.append(random.randint(1, limit)) 35 return arr 36 37 38 if __name__ == '__main__': 39 arr = test_arr(100, 100) 40 arr2 = test_arr(100, 100) 41 print('冒泡排序前', arr) 42 arr = bubble_sort(arr) 43 print('冒泡排序后', arr) 44 print('--------------------') 45 print('冒泡排序前', arr2) 46 arr2 = bubble_sort(arr2) 47 print('冒泡排序后', arr2)