从左到右依次选取一个值作为默认最大值,依次与其它值比较,如果有值比该值大,那最大值指针改指向该值,一轮比较完成后,如果最大值指针没有变化,则从下一个值继续下一轮比较,如果指针有变动,则最新指针位置的数值与初始指针位置数值交换位置。
代码如下:
lst1 = [ [1, 8, 9, 5, 6, 7, 4, 3, 2],
[9, 8, 7, 6, 5, 4, 3, 2, 1],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 1, 1, 1, 3, 1, 1, 1, 2]
]
nums = lst1[0]
length = len(nums)
print(nums)
count_iter = 0
count_swap = 0
for i in range(length):
maxindex = i
for j in range(i + 1, length):
count_iter += 1
if nums[j] > nums[maxindex]:
maxindex = j
if maxindex != i:
nums[maxindex], nums[i] = nums[i], nums[maxindex]
count_swap += 1
print(nums, count_iter, count_swap)
输出结果:
[1, 8, 9, 5, 6, 7, 4, 3, 2][9, 8, 7, 6, 5, 4, 3, 2, 1] 36 6