1 つのアプローチを次に示します。
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 だから 2 に設定b[3]
します。 b: [-1, -1, 2]
a[4] = 5
サブ配列に挿入:[1 ,2, 5, 7]
ソートされた配列の 5 より前の要素はありますか? はい。その 2 だから 2 に設定b[4]
します。 b: [-1, -1, 2, 2]
等々..