Challenge - 5 Problems
Sorting Stability Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this stable sort on objects?
Consider the array of objects sorted by the 'value' key using a stable sort. What is the output after sorting?
DSA Javascript
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));Attempts:
2 left
💡 Hint
Stable sort keeps the original order of equal elements.
✗ Incorrect
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.
🧠 Conceptual
intermediate1:30remaining
Which sorting algorithm is stable by default?
Among the following sorting algorithms, which one is stable by default?
Attempts:
2 left
💡 Hint
Think about which algorithm merges sorted sublists without changing order of equal elements.
✗ Incorrect
Merge Sort is stable because it merges sorted sublists by comparing elements and preserving their order when equal.
❓ Predict Output
advanced2:30remaining
What error or output does this unstable sort produce?
Given this array of objects sorted by an unstable algorithm, what is the output of the ids after sorting by 'value'?
DSA Javascript
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));Attempts:
2 left
💡 Hint
The unstable sort swaps equal elements, changing their original order.
✗ Incorrect
The unstable sort swaps adjacent equal elements, so the original order of equal 'value' elements is reversed in pairs.
🚀 Application
advanced1:30remaining
When should you prefer a stable sort over an unstable sort?
Choose the best scenario where using a stable sort is important.
Attempts:
2 left
💡 Hint
Stable sort preserves order of equal keys, useful for multi-level sorting.
✗ Incorrect
When sorting by multiple criteria, stable sort preserves the order of previous sorts, important for sorting employees by department then joining date.
🧠 Conceptual
expert2:00remaining
Which sorting algorithm is NOT stable and why?
Among the following, which sorting algorithm is NOT stable and what is the main reason?
Attempts:
2 left
💡 Hint
Think about which algorithm changes relative order by moving elements far apart.
✗ Incorrect
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.