NicholasAdamou icon

Problem 1: Merge two sorted arrays

NicholasAdamou | PRO | 09/13/19 11:20:12 PM UTC | 0 ⭐ | 312 👁️ | Never ⏰ | []
Java |

1.77 KB

|

None

|

0 👍

/

0 👎

import java.util.Arrays;
 
public class Main {
    // Give two sorted arrays of the integers, write a function to merge these two arrays.
    // Both arrays can have duplicate elements.
    // EXPECTED OUTPUT: { -12, -6, 5, 11, 12, 17, 21, 25, 33, 39, 41, 41, 44, 49, 50, 50 }
    public static void main(String[] args) {
        int[] a = { 12, 25, 33, 41, 50 };
        int[] b = { -12, -6, 5, 11, 17, 21, 39, 41, 44, 49, 50 };
 
        // STEP 1: Create an array c[] of size a + b.
        int[] c = new int[a.length + b.length];
 
        mergeArrays(a, b, a.length, b.length, c);
 
        System.out.println("EXPECTED OUTPUT: [-12, -6, 5, 11, 12, 17, 21, 25, 33, 39, 41, 41, 44, 49, 50, 50]");
        System.out.println("ACTUAL OUTPUT: " + Arrays.toString(c));
    }
 
    // Merge a[0..n1-1] and b[0..n2-1]
    // into c[0..n1+n2-1].
    private static void mergeArrays(int[] a, int[] b, int n1, int n2, int[] c) {
        int i = 0, j = 0, k = 0;
 
        // STEP 2: Copy all n1 elements of a[] to c[].
        //  - Pick smaller of current elements in a[] and b[],
        //    copy this smaller element to next position in c[]
        //    and move ahead in c[] and the array whose element is picked.
 
        // Traverse both array
        while (i < n1 && j < n2) {
            // Check if current element of first
            // array is smaller than current element
            // of second array. If yes, store first
            // array element and increment first array
            // index. Otherwise do same with second array.
            if (a[i] < b[j]) {
                c[k++] = a[i++];
            } else {
                c[k++] = b[j++];
            }
        }
 
        // STEP 3: Traverse b[] and one by one insert elements (like insertion sort) of c[] to a[].
 
        // Store remaining elements of first array
        while (i < n1) {
            c[k++] = a[i++];
        }
 
        // Store remaining elements of second array
        while (j < n2) {
            c[k++] = b[j++];
        }
    }
}

Comments