klippa

Merge Arrays

Aug 19th, 2022
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.06 KB | None | 0 0
  1. int[] array1 = new int[] { 3, 5, 6, 9, 12, 14, 18, 20, 25, 28 };
  2. int[] array2 = new int[] { 30, 32, 34, 36, 38, 40, 42, 44, 46, 48 };
  3.  
  4. int count1 = array1.Length;
  5. int count2 = array2.Length;
  6. int[] arrayResult = new int[count1 + count2];
  7.  
  8. int a = 0, b = 0;   // indexes in origin arrays
  9. int i = 0;          // index in result array
  10.  
  11. // join
  12. while (a < count1 && b < count2)
  13. {
  14.     if (array1[a] <= array2[b])
  15.     {
  16.         // element in first array at current index 'a'
  17.         // is less or equals to element in second array at index 'b'
  18.         arrayResult[i++] = array1[a++];
  19.     }
  20.     else
  21.     {
  22.         arrayResult[i++] = array2[b++];
  23.     }
  24. }
  25.  
  26. // tail
  27. if (a < count1)
  28. {
  29.     // fill tail from first array
  30.     for (int j = a; j < count1; j++)
  31.     {
  32.         arrayResult[i++] = array1[j];
  33.     }
  34. }
  35. else
  36. {
  37.     // fill tail from second array
  38.     for (int j = b; j < count2; j++)
  39.     {
  40.         arrayResult[i++] = array2[j];
  41.     }
  42. }
  43.  
  44. // print result
  45. Console.WriteLine("Result is {{ {0} }}", string.Join(",", arrayResult.Select(e => e.ToString())));
Add Comment
Please, Sign In to add comment