# # python
# # 冒泡排序:升序排序
# lt = [8, 3, 6, 9, 5, 2, 4, 1, 7]
# n = len(lt)
# # 外出循环控制排序多少轮
# for i in range(n - 1):
# # 内存循环控制相邻两个元素的比较
# for j in range(n - 1 - i):
# if lt[j] > lt[j + 1]:
# # 通用交换元素方式
# # temp = lt[j]
# # lt[j] = lt[j+1]
# # lt[j+1] = temp
# # python中特有方式
# lt[j],lt[j + 1] = lt[j + 1], lt[j]
#
# print(lt)
# temp = lt[j];lt[j] = lt[j+1];lt[j+1] = temp 等价于lt[j], lt[j + 1] = lt[j + 1], lt[j]
选择排序思路:
第一次:找到最小值,存到列表的0坐标位置
第二次:找到次小值,存到列表的1坐标位置
第三次:找到第三小的值,存到列表的2坐标位置
第四次:找到第四小的值,存到列表的3坐标位置
第五次:找到第五小的值,存到列表的4坐标位置 剩下的最后一个位置的数,就是最大值
lt = [8, 3, 6, 9, 5, 2, 4, 1, 7]
for i in range(len(lt)-1):
min_index=i
for j in range(i+1,len(lt)) :
if lt[min_index]>lt[j]:
# temp=lt[min_index]
# lt[min_index]=lt[j]
# lt[j]=temp
lt[min_index],lt[j]=lt[j],lt[min_index]
print(lt)
print(lt)
实现过程如下:
[3, 8, 6, 9, 5, 2, 4, 1, 7]
[2, 8, 6, 9, 5, 3, 4, 1, 7]
[1, 8, 6, 9, 5, 3, 4, 2, 7]
[1, 6, 8, 9, 5, 3, 4, 2, 7]
[1, 5, 8, 9, 6, 3, 4, 2, 7]
[1, 3, 8, 9, 6, 5, 4, 2, 7]
[1, 2, 8, 9, 6, 5, 4, 3, 7]
[1, 2, 6, 9, 8, 5, 4, 3, 7]
[1, 2, 5, 9, 8, 6, 4, 3, 7]
[1, 2, 4, 9, 8, 6, 5, 3, 7]
[1, 2, 3, 9, 8, 6, 5, 4, 7]
[1, 2, 3, 8, 9, 6, 5, 4, 7]
[1, 2, 3, 6, 9, 8, 5, 4, 7]
[1, 2, 3, 5, 9, 8, 6, 4, 7]
[1, 2, 3, 4, 9, 8, 6, 5, 7]
[1, 2, 3, 4, 8, 9, 6, 5, 7]
[1, 2, 3, 4, 6, 9, 8, 5, 7]
[1, 2, 3, 4, 5, 9, 8, 6, 7]
[1, 2, 3, 4, 5, 8, 9, 6, 7]
[1, 2, 3, 4, 5, 6, 9, 8, 7]
[1, 2, 3, 4, 5, 6, 8, 9, 7]
[1, 2, 3, 4, 5, 6, 7, 9, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]