. 1 Import Random 2 . 3 . 4 # original bubble sort . 5 DEF bubble_sort (the nums): . 6 counter = 0 . 7 for I in Range (len (the nums) -. 1): # This loop is responsible for setting the number of times the bubble sort . 8 for J in Range (len (the nums) - I -. 1): # this is the number of comparisons per trip, each starting from 0, the bottom is already ordered . 9 IF the nums [J]> the nums [J +. 1 ]: 10 the nums [ J], the nums [J +. 1] = the nums [J +. 1 ], the nums [J] . 11 counter. 1 = + 12 is Print ( 'Comparison times: ' , counter) 13 is return the nums 14 15 16 # optimization bubble sort . 17 DEF bubble_sort2 (the nums): 18 is counter = 0 . 19 for I in Range (len (the nums) -. 1 ): 20 is ex_flag = False # Set exchange flag, if there is no exchange, indicating that it has sorted completed, no further 21 is for J in Range (len (the nums) -. 1 ): 22 is IF the nums [J]> the nums [J +. 1 ]: 23 is the nums [J], the nums [+ J. 1] = the nums [J +. 1 ], the 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 is test_arr = (100, 100 ) 41 is Print ( ' bubble sort before ' , ARR) 42 is ARR = bubble_sort (ARR) 43 is Print ( ' the bubble sort ' , ARR) 44 is Print ( ' -------------------- ' ) 45 Print ( ' before bubble sort ' , arr2 is) 46 is arr2 is = bubble_sort (arr2 is) 47 Print (' After the bubble sort ' , arr2 is)