Robert Lafo's book, Data Structures and Algorithms in Java, says that Sorting Sorting is a stable algorithm. This means that equal elements maintain their order.
Here is an example from a book:
public void insertionSort() {
int in, out;
for (out = 1; out < nElems; out++)
{
long temp = a[out];
in = out;
while (in > 0 && a[in - 1] >= temp)
{
a[in] = a[in - 1];
--in;
}
a[in] = temp;
}
}
In the loop, whilewe go left and look for a place for the variable temp. And even if a[in - 1] == temp, we still move one step to the left and insert tmpbefore a[in - 1], and in the original array tmp, to the right of a[in - 1].
After sorting, the order of the array elements has changed. How stable is this algorithm then? Shouldn't it be a[in - 1] > tempinstead a[in - 1] >= temp?
Maybe I'm just wrong and I don’t see anything obvious?
source