这是一种方法:
for i ← 1 to i ← (length(A)-1) {
// A[i] is added in the sorted sequence A[0, .. i-1] save A[i] to make a hole at index j
item = A[i]
j = i
// keep moving the hole to next smaller index until A[j - 1] is <= item
while j > 0 and A[j - 1] > item {
A[j] = A[j - 1] // move hole to next smaller index
j = j - 1
}
A[j] = item // put item in the hole
// if there are elements to the left of A[j] in sorted sequence A[0, .. i-1], then store it in b
// TODO : run loop so that duplicate entries wont hamper results
if j > 1
b[i] = A[j-1]
else
b[1] = -1;
}
试运行:
a = 2 1 7 5 7 9
a[1] = 2
直截了当,设置b[1]
为-1
a[2] = 1
插入子数组:[1 ,2]
排序数组中 1 之前的任何元素?不。所以设置b[2]
为 -1 。b: [-1, -1]
a[3] = 7
插入子数组:[1 ,2, 7]
排序数组中 7 之前的任何元素?是的。它的 2 所以设置b[3]
为 2。 b: [-1, -1, 2]
a[4] = 5
插入子数组:[1 ,2, 5, 7]
排序数组中 5 之前的任何元素?是的。它的 2 所以设置b[4]
为 2。 b: [-1, -1, 2, 2]
等等..