1.顺序表排序(插入排序)
3 | 4 | 2 | 1 |
若红字为已经排序好的数字(升序),4>2,则进行移动
2 | |||
3 | 4>> | 1 |
若3>2,将3进行右移
2 | |||
3>> | 4 | 1 |
2 | |||
3 | 4 | 1 |
2 | 3 | 4 | 1 |
2.代码:
# 对顺序表(list)进行排序】
def list_sort(lst):
for i in range(1,len(lst)):
x = lst[i] # 第 i 个元素
j = i
while j >0 and lst[j-1] > x: # 进行升序排序
lst[j] = lst[j-1] # 对元素进行移动
j -= 1
lst[j] = x # 第 i 个元素插入到正确的位置
lst=[4,3,2,1]
list_sort(lst)
print("对list进行排序",lst) # 对list进行排序 [1, 2, 3, 4]