Stabilizing the standard library qsort?

No, you cannot rely on that unfortunately. Let’s assume you have the array (two fields in each record used for checking but only first field used for sorting):

B,1
B,2
A,3

A non-stable sort may compare B,1 with A,3 and swap them, giving:

A,3
B,2
B,1

If the next step were to compare B,2 with B,1, the keys would be the same and, since B,2 has an address less than B,1, no swap will take place. For a stable sort, you should have ended up with:

A,3
B,1
B,2

The only way to do it would be to attach the starting address of the pointer (not its current address) and sort using that as well as the other keys. That way, the original address becomes the minor part of the sort key so that B,1 will eventually end up before B,2 regardless of where the two B lines go during the sorting process.

Leave a Comment