Sorting Stability and When to Use Which Sort in DSA C - Time & Space Complexity
Sorting is a common task in programming, and different sorting methods work differently in speed and behavior.
We want to understand how the time taken by these sorting methods grows as the list size grows.
Analyze the time complexity of the following sorting code snippet.
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
This code sorts an array using Bubble Sort, which compares and swaps adjacent elements repeatedly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing and swapping adjacent elements inside nested loops.
- How many times: Outer loop runs (n-1) times, inner loop runs decreasing times from (n-1) to 1, total roughly n×n times.
As the list size grows, the number of comparisons and swaps grows roughly with the square of the size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 comparisons/swaps |
| 100 | About 10,000 comparisons/swaps |
| 1000 | About 1,000,000 comparisons/swaps |
Pattern observation: Doubling the input size roughly quadruples the work needed.
Time Complexity: O(n²)
This means the time taken grows quickly as the list gets bigger, making it slower for large lists.
[X] Wrong: "Bubble Sort is always slow and never useful."
[OK] Correct: Bubble Sort is stable and simple, making it useful for small or nearly sorted lists where stability matters.
Understanding sorting stability and time complexity helps you choose the right sort for the job and explain your choices clearly in interviews.
"What if we used Merge Sort instead of Bubble Sort? How would the time complexity and stability change?"
Practice
stable?Solution
Step 1: Understand stability in sorting
A stable sort keeps the relative order of elements that compare equal unchanged.Step 2: Compare options with definition
Only It keeps the original order of equal elements after sorting matches this definition exactly.Final Answer:
It keeps the original order of equal elements after sorting -> Option CQuick Check:
Stable sort = keeps order of equal elements [OK]
- Confusing stability with sorting order
- Thinking stability means faster sorting
- Assuming stability relates to memory use
qsort function in C for sorting an array arr of integers with n elements?Solution
Step 1: Recall qsort parameter order
The qsort function parameters are: pointer to array, number of elements, size of each element, and comparison function pointer.Step 2: Match parameters with options
qsort(arr, n, sizeof(int), compare); matches this order exactly: arr, n, sizeof(int), compare.Final Answer:
qsort(arr, n, sizeof(int), compare); -> Option BQuick Check:
qsort syntax = arr, n, size, compare [OK]
- Mixing up size and count parameters
- Placing compare function in wrong position
- Using wrong order of arguments
typedef struct {
int key;
char value;
} Item;
void bubbleSort(Item arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j].key > arr[j+1].key) {
Item temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
Item arr[5] = {{2, 'a'}, {3, 'b'}, {2, 'c'}, {1, 'd'}, {3, 'e'}};
bubbleSort(arr, 5);
for (int i = 0; i < 5; i++) {
printf("%d%c ", arr[i].key, arr[i].value);
}
return 0;
}Solution
Step 1: Understand bubble sort stability
Bubble sort is stable, so equal keys keep their original order.Step 2: Trace sorting of array
Original order for key=2 is 'a' then 'c', for key=3 is 'b' then 'e'. After sorting by key, order is 1d, 2a, 2c, 3b, 3e.Final Answer:
1d 2a 2c 3b 3e -> Option AQuick Check:
Bubble sort stable = keeps order of equal keys [OK]
- Assuming bubble sort is unstable
- Swapping equal keys and changing order
- Mixing up output order of equal keys
void selectionSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
int min_idx = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}Solution
Step 1: Identify why selection sort is unstable
Selection sort swaps min element directly, which can reorder equal elements and break stability.Step 2: Fix by shifting elements
Instead of swapping, shift elements right and insert min element at correct position to keep order.Final Answer:
Replace swap with shifting elements to insert min element -> Option DQuick Check:
Stable selection sort = shift, not swap [OK]
- Just changing comparison operator
- Switching to bubble sort without reason
- Sorting in wrong order
Solution
Step 1: Understand requirements for large data and stability
Large data needs external sorting; stability is required to keep duplicate order.Step 2: Match algorithm features
External merge sort is stable and designed for large data using disk; quicksort and heapsort are unstable and in-memory; selection sort is inefficient.Final Answer:
External merge sort because it is stable and handles large data -> Option AQuick Check:
Large stable sort = external merge sort [OK]
- Choosing quicksort ignoring stability
- Picking heapsort without external support
- Using simple sorts for large data
Ready to prove it?
Pass the test and this pattern moves unknown
