struct Item {
int key;
char name[10];
};
struct Item arr[] = {
{2, "apple"},
{1, "banana"},
{2, "cherry"},
{1, "date"}
};
// After stable sort by key ascending, print names in order
for (int i = 0; i < 4; i++) {
printf("%s ", arr[i].name);
}Stable sort keeps the original order of equal keys.
Since the sort is stable, items with key=1 keep their original order: banana then date. Similarly, items with key=2 keep order: apple then cherry.
Think about sorting by multiple criteria step-by-step.
Stable sorts preserve the order of equal elements, which is important when sorting by multiple fields sequentially (e.g., sort by last name, then by first name).
int arr[] = {4, 2, 2, 3, 4}; // After unstable sort ascending, print array for (int i = 0; i < 5; i++) { printf("%d ", arr[i]); }
Unstable sort may reorder equal elements arbitrarily, but output must be sorted ascending.
Unstable sort guarantees sorted order but does not guarantee original order of equal elements. The output must be sorted ascending, so only option D is sorted ascending.
Consider stability and efficiency for large data.
Merge sort is stable and efficient (O(n log n)) for large datasets, making it suitable when stability is required.
struct Item {
int key;
char name[10];
};
void insertionSort(struct Item arr[], int n) {
for (int i = 1; i < n; i++) {
struct Item temp = arr[i];
int j = i - 1;
while (j >= 0 && arr[j].key >= temp.key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}Check how equal keys are handled in the comparison.
Using '>=' means elements with equal keys are shifted, breaking stability. Using '>' preserves stability by not moving equal keys.
