0 votes
4.8k views
in Java by
How to merge two unsorted arrays in java?. Please give an suitable example.

1 Answer

0 votes
by

You see the following code and understand carefully:

package com;

import java.util.Arrays;

public class MergeTwoUnSortedArray {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int aArr[] = {12, 2, 45, 65};
        int bArr[] = {48, 15, 4, 36, 19, 78, 1};
        
        System.out.println("First  Un-Sorted Array: ");
        for(int i = 0; i < aArr.length; i++){
            System.out.print(aArr[i] + " ");
        }
        System.out.println("\nSecond Un-Sorted Array: ");
        for(int i = 0; i < bArr.length; i++){
            System.out.print(bArr[i] + " ");
        }
        //First of all we needed to sort both arrays
        Arrays.sort(aArr);
        Arrays.sort(bArr);
        System.out.println("\nFirst  Sorted Array: ");
        for(int i = 0; i < aArr.length; i++){
            System.out.print(aArr[i] + " ");
        }
        System.out.println("\nSecond Sorted Array: ");
        for(int i = 0; i < bArr.length; i++){
            System.out.print(bArr[i] + " ");
        }
        int mergedArr[] = doMergeArray(aArr, bArr);
        System.out.println("\nFinal Merged Sorted Array: ");
        for(int i = 0; i < mergedArr.length; i++){
            System.out.print(mergedArr[i] + " ");
        }
    }

    private static int[] doMergeArray(int[] aArr, int[] bArr) {
        int mergedArrLength = aArr.length + bArr.length;
        int mergedArr[] = new int[mergedArrLength];
        int i=0,j=0,k=0;
        //If both arrays having equal number of element or same length
        while(i < aArr.length && j < bArr.length){
            if(aArr[i] <= bArr[j]){
                mergedArr[k] = aArr[i];
                i++;
            }else{
                mergedArr[k] = bArr[j];
                j++;
            }
            k++;
        }
        //If first array having more elements than second array
        while(i < aArr.length){
            mergedArr[k] = aArr[i];
            i++;
            k++;
        }
        //If second array having more elements than first array
        while(j < bArr.length){
            mergedArr[k] = bArr[j];
            j++;
            k++;
        }
        return mergedArr;
    }
}
 

Output:

First  Un-Sorted Array:
12 2 45 65

Second Un-Sorted Array:
48 15 4 36 19 78 1

First  Sorted Array:
2 12 45 65

Second Sorted Array:
1 4 15 19 36 48 78

Final Merged Sorted Array:
1 2 4 12 15 19 36 45 48 65 78

Share:- Whatsapp Facebook Facebook


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

Categories

...