Tech Qu: Merge two sorted arrays
Sorted Array Merge Problem: Design an algorithm to merge two sorted positive integer arrays A and B. Size of array A is n and size of array B is m. Array A has m empty blocks(-1) at random places. Merge array B into A such that array A is sorted and does not have empty blocks.
The approach is simple and reminds me of my old tape handling days. Would be fun if someone describes the problem as two data tapes and see where the reader goes.
A good start would be to define test cases (Boundary cases)
- all of B occurs before any of A.
- all of B occurs after all of A
A simple routine would be to compact A so all of the empty blocks are at the front and then just walk both arrays, picking the smallest number from each array to fill in the resulting array.
- public static int?[] MergeSorted(int?[] a, int?[] b)
- {
- var ai = a.Length - 1;
- var bi = 0;
- var mi=0;
- // Move all nulls to end
- for(int i=a.Length-1; i > -1;i--)
- if(a[i] != null)
- {
- a[ai] = a[i];
- if(ai!=i)
- a[i] = null;
- ai--;
- }
- //point to first non-empty one
- ai++;
- for(var i=0; i < a.Length; i++)
- {
- if (ai < a.Length && bi < b.Length)
- {
- if (a[ai] < b[bi])
- {
- a[i] = a[ai++];
- }
- else
- {
- a[i] = b[bi++];
- }
- }
- else
- if (bi < b.Length)
- {
- a[i] = b[bi++];
- }
- }
- return a;
- }
Unit testing is simple:
- int?[] a = {null, null, 1, 3,null,null};
- int?[] b = { 3,4,5,6};
- var result = Questions.MergeSorted(a, b);
- foreach(var i in result)
- {
- Console.WriteLine(i);
- }
Complexity is O(n) and no extra space is needed.
Comments
Post a Comment