Skip to content

Instantly share code, notes, and snippets.

@Xifeng2009
Created September 14, 2018 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xifeng2009/94d219af9a9864f8af63ea20bda96748 to your computer and use it in GitHub Desktop.
Save Xifeng2009/94d219af9a9864f8af63ea20bda96748 to your computer and use it in GitHub Desktop.
插入排序
import random
Range = 100
Length = 5
list = random.sample(range(Range),Length) #在指定序列中随机获取指定长度片段
print('before sort:',list)
for i in range(1,Length): #默认第一个元素已经在有序序列中,从后面元素开始插入
for j in range(i,0,-1): #逆向遍历比较,交换位置实现插入
if list[j] < list[j-1]:
list[j],list[j-1] = list[j-1],list[j]
print('after sort:',list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment