Skip to content

Instantly share code, notes, and snippets.

@kristianjaeger
Created October 26, 2025 22:06
Show Gist options
  • Select an option

  • Save kristianjaeger/04f6ddd4fe9b99fc43f1159ef76bba85 to your computer and use it in GitHub Desktop.

Select an option

Save kristianjaeger/04f6ddd4fe9b99fc43f1159ef76bba85 to your computer and use it in GitHub Desktop.
Merge two sorted arrays using C#
using System;
// inspired by question 88 on https://leetcode.com/problems/merge-sorted-array
// I couldn't get their c# website compiler / runner to work ;( . I used https://dotnetfiddle.net/ instead to test / run.
public class Solution
{
public int[] Merge(int[] nums1, int m, int[] nums2, int n)
{
int[] merged = new int[n + m];
int i = 0, j = 0, k = 0;
while (i < n && j < m)
{
if (nums1[i] <= nums2[j])
{
merged[k++] = nums1[i++];
}
else
{
merged[k++] = nums2[j++];
}
}
while (i < n)
{
merged[k++] = nums1[i++];
}
while (j < m)
{
merged[k++] = nums2[j++];
}
return merged;
}
static void Main(string[] args)
{
int[] arr1 = {1, 3, 5, 7};
int[] arr2 = {2, 4, 6, 8};
var driver = new Solution();
int[] result = driver.Merge(arr1, arr1.Length, arr2, arr2.Length);
Console.WriteLine(string.Join(", ", result));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment