Problem of the Day
A new programming or logic puzzle every Mon-Fri

Array Merge

Hope everyone had a great Halloween. Welcome to Monday!

Given two sorted arrays, create a function that merges them in to sorted order without using extra space. Try to avoid things such as c = b + a to make it more of a challenge.

Permalink: http://problemotd.com/problem/array-merge/

Comments:

  • Ben - 10 years, 1 month ago

    c#

        public static T[] MergeSortedArrays<T>(T[] array1, T[] array2) where T : IComparable 
        {
            T[] mergedArray = new T[array1.Length + array2.Length];
            int mergedindex = 0;
            int index1 = 0;
            int index2 = 0;
    
            for (int i = mergedindex; i < array1.Length + array2.Length; i++)
            {
                int compareResult = array1[index1].CompareTo(array2[index2]);
                if (compareResult > 0)
                {
                    mergedArray[i] = array2[index2];
                    index2++;
                }
                else
                {
                    mergedArray[i] = array1[index1];
                    index1++;
                }
    
                //we have reached the end of one of the arrays everything else just add to the end
                if (index1 >= array1.Length || index2 >= array2.Length)
                {
                    mergedindex = i;
                    break;
                }
            }
    
            //next item in array
            mergedindex++;
    
            //add rest of array 1
            for (int i = index1; i < array1.Length; i++)
                mergedArray[mergedindex++] = array1[i];
    
            //add rest of array 2
            for (int i = index2; i < array2.Length; i++)
                mergedArray[mergedindex++] = array2[i];
    
            return mergedArray;
        }
    

    reply permalink

Content curated by @MaxBurstein