values = [3, 1, 2]
i = 1
while i < 3:
key = values[i]
j = i - 1
while j >= 0 and values[j] > key:
values[j + 1] = values[j]
j -= 1
values[j + 1] = key
i += 1
i = 0
while i < 3:
print(values[i])
i += 1
输出
1
2
3
生活中的例子
插入一张新的号码牌
工作人员把 2、5、8 号票按顺序摆好了。6 号票应该放在哪里?
初始状态2 5 8 +6
结果2 5 6 8
把8向右挪一位。5后面空出来的位置就是插入点。
添加上午的预约
记事本上已有10点和12点的预约,再加一个9点的预约。
初始状态10 12 +9
结果9 10 12
原有的两个预约都比较晚,各向后移一格就能腾出位置。
在末尾补记一笔付款
按日期排序的账本最后两笔是4日和6日的记录。现在收到7日的付款,哪些记录要挪动?
初始状态4 6 +7
结果4 6 7
原有的最后一个日期就在7日之前。直接追加到末尾,其余记录不用挪。
开销与局限
插入排序适合较短或接近有序的列表。完全逆序时,需要O(n²)次移动和比较。
时间复杂度
最好情况: Θ(n)
平均情况: Θ(n²)
最坏情况: Θ(n²)
用 Python 实现插入排序
Python 源代码
class InsertionSortExample:
def __init__(self):
pass
def insertionSort(self, arr):
for i in range(len(arr)):
temp = arr[i]
holePosition = i
while(holePosition > 0 and arr[holePosition - 1] > temp):
arr[holePosition] = arr[holePosition - 1]
holePosition -= 1
arr[holePosition] = temp
return arr
def printArray(self, arr):
string = " ".join([str(item) for item in arr]);
print(string)
obj = InsertionSortExample()
arr = [15, 3, 12, 6, -9, 9, 0]
print("Before Sorting: ")
obj.printArray(arr)
result = obj.insertionSort(arr)
print("After Sorting: ")
obj.printArray(result)
输出
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
广告
一步步看例子
从 [15, 3, 12, 6, -9, 9, 0] 开始。
先把 15 当作已经排好序的部分,把下一个值 3 暂时存起来。
把15向右移一位,在开头插入3。现在排好序的前段是[3, 15]。
依次处理余下的每个值,插入前只移动比它大的值。相等的值仍按原来的先后顺序排列。
用 Python 实现插入排序:逐步讲解
Python 源代码
class InsertionSortExample:
def __init__(self):
pass
def insertionSort(self, arr):
# Un-sorted array from position 1 to length -1
for i in range(len(arr)):
# Take the left most item in an un-sorted array to temp variable
temp = arr[i]
# Mark the left most position as empty or hole
holePosition = i
# Traverse the sorted array from right to left direction
# Move the item from the sorted array to the empty position (i.e. holePosition) only if the temp variable is less then
# Mark the current item's position as empty by decrementing the value by one
while(holePosition > 0 and arr[holePosition - 1] > temp):
arr[holePosition] = arr[holePosition - 1]
holePosition -= 1
# Once the comparison done, move the value in temp variable to the lastly marked empty position
arr[holePosition] = temp
# Return the sorted array
return arr
def printArray(self, arr):
# Loop the item and print each item in the console with white space seperated
string = " ".join([str(item) for item in arr]);
print(string)
obj = InsertionSortExample()
arr = [15, 3, 12, 6, -9, 9, 0]
print("Before Sorting: ")
obj.printArray(arr)
result = obj.insertionSort(arr)
print("After Sorting: ")
obj.printArray(result)
输出
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15