
public class MergeArrays
{
    public static void main(String[] args)
    {
        double[] list1 = {1, 3, 5, 7, 8};  // Sorted
        double[] list2 = {2, 4, 6, 9};     // Sorted
        double[] r = new double[list1.length + list2.length];
        
        for(int i = 0; i < list1.length; i++)
            System.out.print(list1[i] + " ");
        System.out.println();
        
        for(int i = 0; i < list2.length; i++)
            System.out.print(list2[i] + " ");
        System.out.println();
        
        merge(r, list1, list2);

        for(int i = 0; i < r.length; i++)
            System.out.print(r[i] + " ");
        System.out.println();
    }


    // merge(result, a, b): merge 2 sorted arrays a and b into array result

    public static void merge(double[] result, double[] a, double[] b)      
    {
        int i = 0, j = 0, k = 0; // Indexes for arrays: a[i], b[j], result[k]

        while ( i < a.length || j < b.length )
        {
            if ( i < a.length && j < b.length )
            {  // Both arrays have unprocessed elements
                if ( a[i] < b[j] )
                    result[k++] = a[i++];
                else
                    result[k++] = b[j++];
            }
            else if ( i == a.length ) // a is exhausted (empty)
                result[k++] = b[j++];
            else if ( j == b.length ) // b is exhausted (empty)
                result[k++] = a[i++];
        }
    } 
}
