[ARRAY] Merge 2 Sorted Arrays (one has empty slots)
16 September, 2013 - 2 min read
Question: There are two sorted arrays A1 and A2. Array A1 is full where as array A2 is partially empty and number of empty slots are just enough to accommodate all elements of A1. Write a program to merge the two sorted arrays to fill the array A2. You cannot use any additional memory and expected run time is O(n).
Solution: The trick to solving this problem is to start filling the destination array from the back with the largest elements. You will end up with a merged and sorted destination array.
Code (C#):
// A1 and A2 are two sorted arrays. // A2 is not completely full (has empty slots at the end and are exactly the // size of A1) // the goal is to merge the two arrays in a sorted fashion void Merge(int[] A1, int[] A2) { int count = FindCount(A2); // get the count of full slots int i = A1.Length - 1; int j = count - 1; int k = A2.Length - 1; for(;k>=0;k--) { if(A1[i] > A2[j] || j < 0) { A2[k] =A1[i]; i--; } else { A2[k] = A2[j]; j--; } } }
END