Consider sorting a list of objects by their integer key. Which output shows the list after a stable sort by key?
class Item { int key; String name; Item(int key, String name) { this.key = key; this.name = name; } public String toString() { return key + ":" + name; } } List<Item> items = new ArrayList<>(); items.add(new Item(2, "A")); items.add(new Item(1, "B")); items.add(new Item(2, "C")); items.add(new Item(1, "D")); // After stable sort by key ascending items.sort(Comparator.comparingInt(i -> i.key)); System.out.println(items.stream().map(Item::toString).collect(Collectors.joining(", ")));
Stable sort keeps the original order of equal keys.
Stable sorting keeps the relative order of items with equal keys. Here, items with key 1 appear in original order B then D, and key 2 items appear as A then C.
Which situation best explains when you should use a stable sorting algorithm?
Think about sorting by multiple keys step-by-step.
Stable sorts keep the order of equal elements, which is important when sorting by multiple keys in sequence to preserve previous orderings.
What is the output of this code using an unstable sort on the same list of items?
class Item { int key; String name; Item(int key, String name) { this.key = key; this.name = name; } public String toString() { return key + ":" + name; } } List<Item> items = new ArrayList<>(); items.add(new Item(2, "A")); items.add(new Item(1, "B")); items.add(new Item(2, "C")); items.add(new Item(1, "D")); // Using Collections.sort with a custom comparator (unstable in some implementations) Collections.sort(items, (i1, i2) -> Integer.compare(i1.key, i2.key)); System.out.println(items.stream().map(Item::toString).collect(Collectors.joining(", ")));
Unstable sort may reorder equal keys arbitrarily.
Unstable sorts do not guarantee the order of equal keys, so the relative order of items with key 1 and key 2 may change.
You have a large dataset with many duplicate keys and need to sort it by one key while preserving the order of duplicates. Which sorting algorithm is best?
Consider stability and efficiency for large data.
Merge Sort is stable and has O(n log n) time, making it suitable for large data with duplicates where stability matters.
Given this custom sort code, what causes it to be unstable?
class Item { int key; String name; Item(int key, String name) { this.key = key; this.name = name; } } List<Item> items = new ArrayList<>(); items.add(new Item(1, "X")); items.add(new Item(1, "Y")); items.add(new Item(2, "Z")); items.sort((a, b) -> a.key - b.key); // What causes instability here?
Think about how comparator subtraction can affect order and stability.
Using subtraction in comparator can cause overflow and does not guarantee consistent ordering, leading to instability. Proper comparator should use Integer.compare.
