Bird
0
0
DSA Cprogramming~3 mins

Why Merge Two Sorted Arrays Without Extra Space in DSA C?

Choose your learning style9 modes available
The Big Idea

What if you could merge two sorted lists without needing any extra space at all?

The Scenario

Imagine you have two lists of numbers, each already sorted, and you want to combine them into one sorted list. Doing this by hand means writing down all numbers from both lists and then sorting them again, which takes a lot of time and effort.

The Problem

Manually combining and sorting two lists means you need extra space to hold all numbers together before sorting. This uses more memory and takes longer because you sort everything again, even though the lists were already sorted.

The Solution

This method smartly merges two sorted lists without needing extra space. It rearranges numbers between the two lists step by step, keeping them sorted as it goes, saving memory and time.

Before vs After
Before
int merged[size1 + size2];
for (int i = 0; i < size1; i++) merged[i] = arr1[i];
for (int j = 0; j < size2; j++) merged[size1 + j] = arr2[j];
sort(merged, merged + size1 + size2);
After
for (int i = 0; i < size1; i++) {
  if (arr1[i] > arr2[0]) {
    int temp = arr1[i];
    arr1[i] = arr2[0];
    arr2[0] = temp;
    // Re-sort arr2 to maintain sorted order
  }
}
What It Enables

You can merge two sorted lists efficiently without using extra memory, making programs faster and lighter.

Real Life Example

When your phone merges two contact lists from different apps without creating a big new list, saving space and keeping contacts sorted.

Key Takeaways

Manual merging wastes memory and time by copying and sorting all elements.

This method merges in place by swapping and sorting minimal parts.

It keeps both lists sorted without extra space.