Is there a short, stable sorting algoritm for 4 elements with 5 comparisons and 5 swaps?
I'm looking for an algorithm like https://stackoverflow.com/a/50303723/97248 in terms of length and complexity, but which is stable. This one is not stable: for example, for input [60, 61, 52, 73], with comparison function which ignores the last digit, the result is [52, 61, 60, 73], and the correct stable result would be [52, 60, 61, 73].
It seems to be possible if we track swaps that could (potentially) introduce an inversion of two equal values. This can happen when a swap concerns non-adjacent values, which will be needed at least once if we want to keep the number of comparisons/swaps at five. Such potential inversion will then determine whether a next comparison should be done with
>or>=.To test "stableness", I tested with (key, index) pairs where only the keys influence the comparison, while the index can be used to verify that the original relative order was not altered when keys are the same.
Here is an implementation in JavaScript:
Note that the
inversionvariables are only there to avoid a nested tree ofif ... elseblocks to mimic the same states.