I write this function for merging two arrays.
private static int[] Merge(int[] array1, int[] array2)
{
var mergedArray = new int[array1.Length + array2.Length];
int i = 0, j = 0, k = 0;
while(k < mergedArray.Length)
{
if(i == array1.Length || j == array2.Length)
{
if (i <= j)
{
mergedArray[k] = array1[i];
i++;
}
else
{
mergedArray[k] = array2[j];
j++;
}
}
else
{
if(array1[i] < array2[j])
{
mergedArray[k] = array1[i];
i++;
}
else
{
mergedArray[k] = array2[j];
j++;
}
}
k++;
}
return mergedArray;
}
How to reduce if statements in this code?
You can also make a Linq friendly version. This one is fast and will work on IEnumerable. You could easily translate this to any type T where T is IComparable.
private static IEnumerable<int> Merge(IEnumerable<int> enum1, IEnumerable<int> enum2)
{
IEnumerator<int> e1 = enum1.GetEnumerator();
IEnumerator<int> e2 = enum2.GetEnumerator();
bool remaining1 = e1.MoveNext();
bool remaining2 = e2.MoveNext();
while (remaining1 || remaining2)
{
if (remaining1 && remaining2)
{
if (e1.Current > e2.Current)
{
yield return e2.Current;
remaining2 = e2.MoveNext();
}
else
{
yield return e1.Current;
remaining1 = e1.MoveNext();
}
}
else if (remaining2)
{
yield return e2.Current;
remaining2 = e2.MoveNext();
}
else
{
yield return e1.Current;
remaining1 = e1.MoveNext();
}
}
}
Not as good as the Linq solution, but if you want the traditional if-then style function you could write:
private static int[] Merge(int[] array1, int[] array2)
{
var mergedArray = new int[array1.Length + array2.Length];
int i = 0, j = 0, k = 0;
while(k < mergedArray.Length)
{
if (j == array2.Length || ((i < array1.Length) && (array[i] < array2[j])))
{
mergedArray[k] = array1[i];
i++;
}
else
{
mergedArray[k] = array2[j];
j++;
}
k++;
}
return mergedArray;
}
(edit: missing brace added)
If array2 is empty or if there are still values in array 1 and array1[i] is less than array2[j], then take value from array1, otherwise take from array 2
private static int[] Merge(int[] array1, int[] array2)
{
var mergedArray = new int[array1.Length + array2.Length];
int i = 0, j = 0;
while(i+j < mergedArray.Length)
if (j == array2.Length || ((i < array1.Length) && (array1[i] < array2[j])))
mergedArray[i+j] = array1[i++];
else
mergedArray[i+j] = array2[j++];
return mergedArray;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With