Answer to Question #128387 in C# for MD RASEL BHUYAN

Question #128387
Write a function that will merge the contents of two sorted (ascending order)
arrays of type double values, storing the result in an array output parameter
(still in ascending order). The function should not assume that both its input
parameter arrays are the same length but can assume that one array does not
contain two copies of the same value. The result array should also contain no
duplicate values.
Hint: When one of the input arrays has been exhausted, do not forget to copy
the remaining data in the other array into the result array.
Test your function with cases in which (1) the first array is exhausted first, (2) the second array is exhausted first, and (3) the two arrays are exhausted at the same time (i.e., they end with the same value). Remember that the arrays input to this function
must already be sorted .
1
Expert's answer
2020-08-06T03:59:12-0400
    double[] merge(double[] firstArr, double[] secondArr)
    {
      double[] resArr = new double[firstArr.Length + secondArr.Length];

      int firstPos = 0, secondPos = 0, resPos = 0;
      double a, b;

      while (firstPos < firstArr.Length && secondPos < secondArr.Length)
      {
        a = firstArr[firstPos];
        b = secondArr[secondPos];

        if (a < b)
        {
          resArr[resPos++] = a;
          firstPos++;
        }
        else if (a > b)
        {
          resArr[resPos++] = b;
          secondPos++;
        }
        else
        {
          resArr[resPos++] = a;  // or b
          firstPos++;
          secondPos++;
        }
      }

      if (firstPos >= firstArr.Length)
      {
        for (int i = secondPos; i < secondArr.Length; i++)
          resArr[resPos++] = secondArr[i];
      }
      else  // secondPos >= secondArr.Length
      {
        for (int i = firstPos; i < firstArr.Length; i++)
          resArr[resPos++] = firstArr[i];
      }

      Array.Resize(ref resArr, resPos);       

      return resArr;
    }

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS