• Register

Share:- Whatsapp Facebook Facebook

------------------------------------- Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

0 votes
68 views
How to merge two sorted arrays into a sorted array in java?
int a[] = {2,4,6,8,10};
int b[] = {3,5,7,9,11,13};
int sortedArray[]={2,3,4,5,6,7,8,9,10,11};
in Data Structure And Algorithm by

1 Answer

0 votes
See the bellow example for merging two sorted arrays into a sorted array.

package ds.dsalgo.com.array;

public class MergeTwoSortedArray {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int a[] = {2,4,6,8,10};
        int b[] = {3,5,7,9,11,13};
        System.out.print("First Array:");
        for(int i=0; i<a.length-1;i++){
            System.out.print(" "+a[i]);
        }
        System.out.print("\nSecond Array:");
        for(int i=0; i<b.length-1;i++){
            System.out.print(" "+b[i]);
        }
        int m[] = doMergeTwoSortedArray(a,b);
        System.out.print("\nSorted Array:");
        for(int i=0; i<m.length-1;i++){
            System.out.print(" "+m[i]);
        }
    }
   
    public static int[] doMergeTwoSortedArray(int a[], int b[]){
        int m[] = new int[a.length + b.length];
       
        int i, j, k;
        i=j=k=0;
        while(i < a.length && j < b.length){
            if(a[i] < b[j]){
                m[k] = a[i];
                i++;
            }else{
                m[k] = b[j];
                j++;
            }
            k++;
        }
       
        while(i < a.length){
            m[k] = a[i];
            i++;
            k++;
        }
       
        while(j < b.length){
            m[k] = b[j];
            j++;
            k++;
        }
        return m;
    }

}

Output:-
First Array: 2 4 6 8
Second Array: 3 5 7 9 11
Sorted Array: 2 3 4 5 6 7 8 9 10 11
by (3.2k points)
...