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

标签 java algorithm sorting

在 Robert Lafore 的“Data Structures and Algorithms in 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] > temp 而不是 a[in - 1] >= temp 吗?

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

最佳答案

你完全正确。这是 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] > key 是正确的。在您的情况下,它应该是“a[in - 1] > temp”。 很好地注意到它。 :)

关于java - 相等元素在插入排序算法中是否保留它们的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46839540/

相关文章:

python - 如何使 np.argsort 将空字符串放置在数组的末尾而不是开头

sorting - HeapSort 与 MergeSort 空间复杂度

java - 重新登录时处理通知数据 Android

java - libGDX:如何将纹理裁剪为圆形

algorithm - Amazon 的 Statistically Improbable Phrases 如何运作?

algorithm - 给定一个函数 rand7(),编写一个函数 rand10() 统一

java - 以类名作为类型的方法

java - 尝试resttemplate getforobject时出现404错误

algorithm - 计算大 O 符号的值是否有效?

java - 对可能包含数字的字符串进行排序