【问题标题】:Do equal elements preserve their order in Insertion Sort algorithm?相等的元素是否在插入排序算法中保留它们的顺序?
【发布时间】:2017-10-19 22:00:00
【问题描述】:

在 Robert Lafore 的“Java 中的数据结构和算法”一书中,指出插入排序是一种稳定的算法。这意味着相等的项目保留它们的顺序。

这是书中的例子:

public void insertionSort() {
    int in, out;
    for (out = 1; out < nElems; out++) // out is dividing line
    {
        long temp = a[out]; // remove marked item
        in = out; // start shifts at out
        while (in > 0 && a[in - 1] >= temp) // until one is smaller,
        {
            a[in] = a[in - 1]; // shift item right,
            --in; // go left one position
        }
        a[in] = temp; // insert marked item
    } // end for
} // end insertionSort()

while 循环中,我们将向左移动并为temp 变量寻找位置。即使a[in - 1] == temp,我们仍然向左移动一步,并在a[in - 1] 之前插入tmp,而在原始数组中tmp 位于a[in - 1] 的右侧。

排序后数组元素的顺序发生了变化。那么这个算法如何稳定呢?不应该只有a[in - 1] &gt; temp 而不是a[in - 1] &gt;= temp 吗?

也许我只是犯了一个错误,没有看到明显的东西?

【问题讨论】:

  • 根据定义,“有序项目保留其顺序”适用于所有(正确的)排序算法。 “稳定”排序意味着相同的项目保持其顺序。
  • 任何排序都会改变不相等的项目。使排序稳定的原因是它以与之前相同的相对顺序保持相同的项目。 (例如,对表中的不同列进行排序将使每个类别中的行保持子排序。)
  • 从我在心理调试中看到的算法不稳定,因此是错误的,它应该是&gt; temp。您应该通过实际调试来验证它。
  • 尝试调试,">=" 更改顺序,而 ">" 似乎工作正常。试题好像有错误,我不敢相信。

标签: java algorithm sorting


【解决方案1】:

你完全正确。这是 Thomas H. Cormen 的畅销书“算法简介”中插入排序算法的一个 sn-p。

INSERTION-SORT(A)
1. for j=2 to A.length
2. key = A[j]
3. // Insert A[j] into the sorted sequence A[1..j-1].
4. i = j-1
5. while i > 0 and A[i] > key
6. A[i+1] = A[i]
7. i = i-1
8. A[i+1] = key

如你所见,A[i] > 键是正确的。在您的情况下,它应该是“a [in - 1] > temp”。 很好地注意到它。 :)

【讨论】:

    猜你喜欢
    • 2018-08-19
    • 2012-10-23
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 2011-11-05
    相关资源
    最近更新 更多