About NewTechnoBuzz
Advertise
Contact Us

Wednesday, July 23, 2014

How to merge two arrays in a single sorted array

This is question is one of those java interview questions that an interviewer may ask. Most of the time, an interviewer asks this question from the candidate in different forms like I want to merge two arrays in a single array in sorted order, I have two lists and I want to merge those lists in sorted order in a single list.

Along with writing the algorithm, interviewer may ask you about the time-space complexity of your algorithm in order to check your data structure concepts. Most of the programmers overlook the data structure concepts because Java API provides a rich set of classes.

Now, lets see the solution to merge two arrays in a single sorted array:
package com.gsms.console.test;
import java.util.Arrays;

public class TestJava {

    public static void main(String[] args) {

        int[] array1 = { 23, 47, 81, 95 };
        int[] array2 = { 7, 14, 39, 55, 62, 74 };
        int[] array3 = new int[array1.length + array2.length];

        Arrays.sort(array1);
        Arrays.sort(array2);

        merge(array1, array1.length, array2, array2.length, array3);
        for (int i : array3) {
            System.out.print(i + " ");
        }
    }

    public static void merge(int[] array1, int size1, int[] array2, int size2, int[] array3) {
        int index1 = 0, index2 = 0, index3 = 0;

        while (index1 < size1 && index2 < size2) {
            if (array1[index1] < array2[index2]) {
                array3[index3++] = array1[index1++];
            }
            else {
                array3[index3++] = array2[index2++];
            }
         }

         while (index1 < size1) {
             array3[index3++] = array1[index1++];
         }

         while (index2 < size2) {
             array3[index3++] = array2[index2++];
         }
    }
}

Output
7 14 23 39 47 55 62 74 81 95

Please provide comments, suggestions and feedback to make the content more valuable and to remove if any mistakes occurred.

0 comments