Skip to content

Instantly share code, notes, and snippets.

@kpol
Created March 5, 2018 22:24
Show Gist options
  • Select an option

  • Save kpol/f845e7fb354a920f6b6e394edbbd844e to your computer and use it in GitHub Desktop.

Select an option

Save kpol/f845e7fb354a920f6b6e394edbbd844e to your computer and use it in GitHub Desktop.
Merger two sorted arrays.
/// <summary>
/// Merge two sorted arrays.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static IEnumerable<int> Merge(int[] a, int[] b)
{
int i = 0;
int j = 0;
while (i < a.Length || j < b.Length)
{
if (j == b.Length || a[i] < b[j])
{
yield return a[i];
i++;
}
else if (i == a.Length || a[i] > b[j])
{
yield return b[j];
j++;
}
else
{
yield return a[i];
yield return b[j];
i++;
j++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment