Ask Question
8 September, 01:38

Write the following method that merges two sorted arrays into a new sorted array public static int [] merge (int [] array1, int [] array2) { / / add your code here } public static void main (String [] args) { int [] array1 = {1, 5, 16, 61, 111}; int [] array 2 = {2, 4, 5, 6} int [] mergedArray = merge (array1, array2); System. out. println (Arrays. toString (mergedArray)); } java doc

+3
Answers (1)
  1. 8 September, 01:51
    0
    See explaination

    Explanation:

    import java. util. Arrays;

    public class MergeArrays {

    public static int[] merge (int[] array1, int[] array2) {

    int[] result = new int[array1. length + array2. length];

    int i = 0, j = 0, k = 0;

    while (i < array1. length && j < array2. length) {

    if (array1[i] < array2[j]) result[k++] = array1[i++];

    else result[k++] = array2[j++];

    }

    while (i < array1. length) result[k++] = array1[i++];

    while (j < array2. length) result[k++] = array2[j++];

    return result;

    }

    public static void main (String[] args) {

    int[] array1 = {1, 5, 16, 61, 111};

    int[] array2 = {2, 4, 5, 6};

    int[] mergedArray = merge (array1, array2);

    System. out. println (Arrays. toString (mergedArray));

    }

    }
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Write the following method that merges two sorted arrays into a new sorted array public static int [] merge (int [] array1, int [] array2) ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers