在插入排序算法中,相等元素是否保留了它们的顺序?

时间:2017-10-19 22:00:00

标签: java algorithm sorting

在Java中的"数据结构和算法" Robert Lafore的书称,插入排序是一种稳定的算法。这意味着相同的项目可以保留他们的订单。

以下是本书的例子:

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,我们仍向左移动一步并在tmp之前插入a[in - 1],而原始数组tmp中的a[in - 1]位于a[in - 1] > temp的右侧。 / p>

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

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

1 个答案:

答案 0 :(得分:4)

你是对的。这是Thomas H. Cormen着名的“算法导论”一书中插入排序算法的片段。

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]&gt;关键是正确的。在你的情况下应该是“a [in - 1]&gt; temp”。 很好地注意到它。 :)

相关问题