We combine two sorted lists into one sorted order without using extra storage by swapping and sorting in place.
Analogy: Imagine two sorted stacks of books on two tables. Instead of moving all books to a new table, you swap books between tables to keep both stacks sorted without extra space.
Swap the out-of-place elements to maintain sorted order across arrays
sort_array(arr1, size1); sort_array(arr2, size2);
Sort both arrays after swap to restore order
OutputSuccess
1 2 3 5 8 9
10 13 15 20
Complexity Analysis
Time: O(n * m * (n + m)) because for each element in first array we may swap and sort both arrays which costs O(n + m) each time
Space: O(1) because no extra arrays or data structures are used, only swaps and in-place sorting
vs Alternative: Naive approach uses extra space O(n + m) to merge and then sort once, which is faster but uses more memory
Edge Cases
One or both arrays are empty
No swaps or sorting needed, arrays remain as is
DSA C
for (int i = 0; i < size1; i++) { if (arr1[size1 - 1] > arr2[0]) { ... } }
Arrays already fully sorted with no overlapping values
No swaps occur, arrays remain unchanged
DSA C
if (arr1[size1 - 1] > arr2[0]) {
Arrays with duplicate values
Duplicates are handled naturally by sorting after swaps
DSA C
sort_array(arr1, size1); sort_array(arr2, size2);
When to Use This Pattern
When asked to merge two sorted arrays without extra space, use swapping and in-place sorting to maintain order without additional memory.
Common Mistakes
Mistake: Trying to merge by shifting elements manually without sorting after swaps Fix: Always sort both arrays after swapping to restore sorted order
Mistake: Not comparing last element of first array with first element of second array Fix: Compare arr1[size1 - 1] with arr2[0] to find out-of-place elements
Summary
Merges two sorted arrays into sorted order without using extra space by swapping and sorting in place.
Use when memory is limited and you cannot allocate extra arrays for merging.
The key insight is to swap out-of-place elements between arrays and then sort each array to maintain order.