Sure. It's not something that comes up with simple values like numbers because you can't distinguish between a 3 and another 3; they're identical. But it's important when you have more complex data. Take this array of arrays as an example:
Suppose we want to sort the arrays in ascending order based on the first item of each array, disregarding the second item. A stable sort will preserve the order of equivalent items relative to each other, like this:
Notice how all of the 3s retain their "first", "second", "third" order, which is the same order that they were in relative to each other in the original array. Same thing for the 7s and the 9s.
An unstable sort does not have this guarantee. A non-stable sort may produce something like this instead:
The items are still ordered according to the numbers, but notice how the items with the same numbers aren't necessarily in the same order as in the original array.
Stable sorts allow sorts to be stacked, so you can sort by one key, then by another (e.g. by last name, then first name). You can't do that with an unstable sort because once it goes through an unstable sort, the previous order is gone.
View all comments
Show parent comment
15
u/Oneshotkill_2000 Mar 23 '22
I didn't understand the "stable" part, do you have an example on it?