[Solved] Merging sorted lists – C# [closed]


You want to check if you are at the end of your array. If you are, you want to put the largest number at the last index:

static int[] Func(int[] array1, int [] array2)
{
    int[] result = new int [array1.Length + array2.Length];

    int first =0; 
    int second = 0; 
    int current = 0;

    while (current < result.Length) 
    {
        if (array1[first] > array2[second])
        {
            if (current != result.Length - 1)
            {
                result[current] = array2[second];
            }
            else
            {
                 result[current] = array1[first];
            }

            if (second < array2.Length - 1) second++;
        }
        else if (array1[first] < array2[second])
        {
            result[current] = array1[first];
            if (first < array1.Length - 1) first++;
        }
        current++;
    }
    return result;
}

You could also implement it in this way:

static int[] Func(int[] array1, int[] array2)
{
    int[] result = new int[array1.Length + array2.Length];

    Array.Copy(array1, result, array1.Length);
    Array.Copy(array2, 0, result, array1.Length, array2.Length);

    Array.Sort(result);

    return result;
}

solved Merging sorted lists – C# [closed]