升序
import random l = [] for i in range(8): l.append(random.randint(0,9)) print(l) for cur in range(1,len(l)): tmp = l[cur] index = cur while index >= 0 and tmp <= l[index]: if index - 1 >= 0: l[index] = l[index-1] index -= 1 l[index+1] = tmp print(l)
降序
import random l = [] for i in range(10): l.append(random.randint(0,9)) print(l) len = len(l) cur=len-2 while cur >= 0: tmp = l[cur] index = cur while index < len and tmp <= l[index]: if index + 1 < len: l[index] = l[index+1] index += 1 l[index-1] = tmp cur -= 1 print(l)