const arr = [
{id: 1, value: 3},
{id: 2, value: 1},
{id: 3, value: 3},
{id: 4, value: 2}
];
const sorted = arr.slice().sort((a, b) => a.value - b.value);
console.log(sorted.map(o => o.id));The sort is stable, so elements with the same 'value' keep their original order. Both objects with value 3 (id 1 and 3) remain in the order they appeared.
Merge Sort is stable because it merges sorted sublists by comparing elements and preserving their order when equal.
const arr = [
{id: 'a', value: 5},
{id: 'b', value: 3},
{id: 'c', value: 5},
{id: 'd', value: 3}
];
// Simulate unstable sort by swapping equal elements
function unstableSort(array) {
array.sort((x, y) => x.value - y.value);
// Swap equal elements to simulate instability
for (let i = 0; i < array.length - 1; i++) {
if (array[i].value === array[i + 1].value) {
[array[i], array[i + 1]] = [array[i + 1], array[i]];
i++;
}
}
return array;
}
const sorted = unstableSort(arr);
console.log(sorted.map(o => o.id));The unstable sort swaps adjacent equal elements, so the original order of equal 'value' elements is reversed in pairs.
When sorting by multiple criteria, stable sort preserves the order of previous sorts, important for sorting employees by department then joining date.
Heap Sort is not stable because it builds a heap and swaps elements that can be far apart, changing the relative order of equal elements.
