算法之选择排序
简单选择排序
- 选择排序
- 每一趟两两比较大小,找出极值(极大值或极小值)并放置到有序区的位置。
核心算法
- 结果可为升序或降序排列,默认升序排列。以降序为例
- 扩大有序区,减小无序区。图中红色部分就是增大的有序区,反之就是减小的无序区
- 相邻元素依次两两比较,获得每一次比较后的最大值,并记住此值的索引
- 每一趟都从无序区中选择出最大值,然后交换到当前无序区最左端
nums = [1, 9, 8, 5]
print(nums)
length = len(nums)
for i in range(length - 1):
maxindex = i
for j in range(i+1, length):
if nums[j] > nums[maxindex]:
maxindex = j
nums[i], nums[maxindex] = nums[maxindex], nums[i]
print(nums, i, maxindex)
if i == 0: break
执行结果:[1, 9, 8, 5] # 代码第2行打印的nums的值
执行结果:[9, 1, 8, 5] 0 1 # break 终止的第一次交换
nums = [1, 9, 8, 5]
print(nums)
length = len(nums)
for i in range(length - 1):
maxindex = i
for j in range(i+1, length):
if nums[j] > nums[maxindex]:
maxindex = j
nums[i], nums[maxindex] = nums[maxindex], nums[i]
print(nums, i, maxindex)
执行结果:[1, 9, 8, 5] # 代码第2行打印的nums的值
执行结果:[9, 1, 8, 5] 0 1
执行结果:[9, 8, 1, 5] 1 2
执行结果:9, 8, 5, 1] 2 3
上面代码中我们就实现了选择排序
选择排序优化
num_list = [[1, 9, 8, 5], [9, 1, 8, 5]]
nums = num_list[1]
print(nums)
length = len(nums)
count_iter = 0
count_swap = 0
for i in range(length // 2):
maxindex = i
minindex = -i-1
for j in range(i+1, length):
count_iter += 1
if nums[j] > nums[maxindex]:
maxindex = j
if nums[minindex] > nums[-j-1]:
minindex = -j-1
print(maxindex, minindex, '+++')
if i != maxindex:
nums[i], nums[maxindex] = nums[maxindex], nums[i]
count_swap += 1
break
执行结果:[9, 1, 8, 5]
执行结果:0 -3 +++
num_list = [[1, 9, 8, 5], [9, 1, 8, 5]]
nums = num_list[1]
print(nums)
length = len(nums)
count_iter = 0
count_swap = 0
for i in range(length // 2):
maxindex = i
minindex = -i-1
minorigin = minindex
for j in range(i+1, length):
count_iter += 1
if nums[j] > nums[maxindex]:
maxindex = j
if nums[minindex] > nums[-j-1]:
minindex = -j-1
print(maxindex, minindex, '+++')
if i != maxindex:
nums[i], nums[maxindex] = nums[maxindex], nums[i]
count_swap += 1
if minorigin != minindex:
nums[minorigin], nums[minindex] = nums[minindex], nums[minorigin]
count_swap += 1
print(nums, i, maxindex)
print('_' * 30)
print(nums, count_iter, count_swap)
执行结果:
[9, 1, 8, 5]
0 -3 +++
[9, 5, 8, 1] 0 0
2 -3 +++
[9, 5, 8, 1] 1 2
______________________________
[9, 5, 8, 1] 5 3
最后得到的结果并不是按序排的
num_list = [[1, 9, 8, 5], [9, 1, 8, 5]]
nums = num_list[1]
print(nums)
length = len(nums)
count_iter = 0
count_swap = 0
for i in range(length // 2):
maxindex = i
minindex = -i-1
minorigin = minindex
for j in range(i+1, length):
count_iter += 1
if nums[j] > nums[maxindex]:
maxindex = j
if nums[minindex] > nums[-j-1]:
minindex = -j-1
print(maxindex, minindex, '+++')
if i != maxindex:
nums[i], nums[maxindex] = nums[maxindex], nums[i]
count_swap += 1
if i == minindex or i == length + minindex:
minindex = maxindex - length
if minorigin != minindex:
nums[minorigin], nums[minindex] = nums[minindex], nums[minorigin]
count_swap += 1
print(nums, i, maxindex)
print('_' * 30)
print(nums, count_iter, count_swap)
执行结果:
[9, 1, 8, 5]
0 -3 +++
[9, 5, 8, 1] 0 0
2 -3 +++
[9, 8, 5, 1] 1 2
______________________________
[9, 8, 5, 1] 5 2