1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
m_list = [[1,9,8,5,6,7,4,3,2],[1,2,3,4,5,6,7,8,9],[9,8,7,6,5,4,3,2,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,2]] nums = m_list[4] length = len(nums) print(nums) count_swap = 0 count_iter = 0
for i in range(length // 2): maxindex = i minindex = -i - 1 minorigin = minindex for j in range(i + 1, length - i): count_iter += 1 if nums[maxindex] < nums[j]: maxindex = j if nums[minindex] > nums[-j - 1]: minindex = -j -1 print(maxindex,minindex) if nums[maxindex] == nums[minindex]: break if i != maxindex: tmp = nums[i] nums[i] = nums[maxindex] nums[maxindex] = tmp count_swap += 1 if i == minindex or i == length + minindex: minindex = maxindex if minorigin != minindex and nums[minorigin] != nums[minindex]:
tmp = nums[minorigin] nums[minorigin] = nums[minindex] nums[minindex] = tmp count_swap += 1 print(nums, count_swap, count_iter) 输出: [1, 1, 1, 1, 1, 1, 1, 1, 1, 2] 9 -2 1 -2 [2, 1, 1, 1, 1, 1, 1, 1, 1, 1] 1 16
|