检查维基百科页面上有关插入排序的伪代码:
i ← 1
while i < length(A)
j ← i
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j ← j - 1
end while
i ← i + 1
end while
请说明为什么文献中这样说:
The number of exchanges used by insertion sort is equal to the number of
inversions in the array, and the number of compares is at least equal to
the number of inversions and at most equal to the number of inversions
plus the array size minus 1.
一次相邻元素交换(即“当前选定元素”与已排序子数组中的元素(即从原始数组的左端开始))只会删除一次反转。
但是对于给定的元素列表,引入一次交换可以添加许多反转;假设列表:123
,通过将元素3
与元素交换1
,会引入3
反转。
所需的比较次数为三次:
i=1:<2,3>, i=2:<1,3>, <1,2>
此外,列表中反转的次数为三次:321
这个反转次数也是由给出的nC2
,其中n
是列表大小。
假设,对于大小为 的反向排序列表4: 4321
,有六个反转:<4,3>,<4,2>,<4,1>,<3,2>,<3,1>,<2,1>
,这也是 n 集的 2 子集的数量。在这两个问题中,由于不涉及排序,有 需要计算的组合数。
插入排序对反向排序列表的应用所涉及的步骤(比较+交换)<4321>
如下:
1. i ← 1, j ← 1, A[0] > A[1]: swap A[1] and A[0], j ← 0: <3421>
2. i ← 2, j ← 2, A[1] > A[2]: swap A[2] and A[1], j ← 1: <3241>
j ← 1, A[0] > A[1]: swap A[1] and A[0], j ← 0: <2341>
3. i ← 3, j ← 3, A[2] > A[3]: swap A[3] and A[2], j ← 2: <2314>
j ← 2, A[1] > A[2]: swap A[2] and A[1], j ← 1: <2134>
j ← 1, A[0] > A[1]: swap A[1] and A[0], j ← 0: <1234>
但是,无法理解何时最大比较次数等于number of inversions + array size -1
;至于大小为的反向排序数组的最坏情况n
;反转次数等于nC2
。
其余的比较从何而来,即'n-1'
比较?
上面提到的文献指出这些'n-1'
比较的来源是:
additional compare might happen for the value of `i` from `1` to `n-1` (when `a[i]` does not reach the left end of the array).
括号中的部分引起了混淆;其含义如下:(when a[i] does not reach the left end of the array).
这种情况可能意味着列表的情况,其中“第一个元素”(i=0)
位于其最终位置,例如:1423
。或者换句话说,它是否谈论all the possible
比较,包括存在no
反转的比较。
假设,对于1423
,有两个反转,但需要进行额外的比较:<1,4>, <1,2>, <1,3>, <2,3>
。但是,这些是四次比较,而不是三次(数组大小:4 减 1)。
也不清楚文献中使用的措辞,因为算法中没有明确显示这样的比较。
同一文献在此处列出了用于插入排序的 C++ 代码,但也没有明确显示任何此类比较。