Merge two sorted arrays in java.

 import java.util.Scanner;

public class Main

{

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("enter first array size=");

int n=sc.nextInt();

System.out.println("enter second array size=");

int m=sc.nextInt();

int[] arr=new int[n];

int[] brr=new int[m];

System.out.println("enter sorted elements of first array=");

for(int i=0; i<n; i++){

      arr[i]=sc.nextInt();

}

System.out.println("\nenter sorted elements of second array=");

for(int i=0; i<m; i++){

      brr[i]=sc.nextInt();

}

int[] crr=new int[n+m];

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

while(i<n && j<m){

    if(arr[i]<=brr[j]){

    crr[k]=arr[i];

    i++;

    }

    else{

        crr[k]=brr[j];

        j++;  

    }

    k++;

}

if(i==n){

      while(j<m){

        crr[k]=brr[j];

        j++;

        k++;

      }

}

if(j==m){

      while(i<n){

        crr[k]=arr[i];

        i++;  

        k++;

      }

}

System.out.println("Merged array is=");

for(int ele:crr){

      System.out.print(ele+" ");

}

}

}

output->

enter first array size=

4

enter second array size=

6

enter sorted elements of first array=

12

23

33

56


enter sorted elements of second array=

22

34

55

58

60

78

Merged array is=

12 22 23 33 34 55 56 58 60 78 

Comments

Popular posts from this blog

Introduction of java Programming language.

Stack data structure.