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?
Not as good as the Linq solution, but if you want the traditional if-then style function you could write:
(edit: missing brace added)
Or in English:
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
Or very concise (just for fun):