Merge two array and sort the merge array

Khurshid Md Anwar
2 min readMay 11, 2021

--

Q. Write a program in Java to accept two integer arrays from the user and join them into a third array.

Q. Write a program in Java to accept two integer arrays from the user and join them into a third array.

After joining the arrays, sort the final array in ascending order using the Bubble sort technique.

Sample Input: Array A [ ] = {10,2,23,4,15};

Array B [ ] = {60,7,80,99,10};

Sample Output: The final Array after

joining is :

10 2 23 4 15 60 7 80 99 10

The final Array after sorting is: 2 4 7 10 10 15 23 60 80 99

Solution:

In the following program, two array arr1[] and arr2[] are merged into a single array arr3[]. Here first array arra1[] with five values first added to one by one to the third arr3[] and then arr2[] five values are added to arr3[]. After merging we sort the array with the Bubble sort array technique. Finally, we print the sorted array.

public class MergeArrayAndSort

{

public static void main(String args[])

{

int arr1[]={10,2,23,4,15}; // First Array

int arr2[]={60,7,80,99,10}; // Second Array

int arr3[]=new int[10]; // Third Array

int i, k=0; // use as a counter for third array

int j, temp;

System.out.println(“First Array”);

for(i=0; i<5; i++)

{

System.out.print(arr1[i] + “ “);

}

System.out.println();

System.out.println(“Second Array”);

for(i=0; i<5; i++)

{

System.out.print(arr2[i] + “ “);

}

System.out.println();

// Merging of two array

// First array into the third array

for(i=0; i<5; i++)

{

arr3[k]=arr1[i];

k++; //k=5

}

// Second array into the third array

for(i=0; i<5; i++)

{

arr3[k]=arr2[i];

k++;

}

System.out.println(“After Merging of Two arrays into third array”);

for(i=0; i<k; i++)

{

System.out.print(arr3[i] + “ “);

}

System.out.println();

// Sort the Merge Array with Bubble sort

for(i=0; i<k-1; i++)

{

for(j=0; j<k-1 — i; j++)

{

if(arr3[j]>arr3[j+1])

{

temp = arr3[j];

arr3[j] = arr3[j+1];

arr3[j+1] = temp;

}

}

}

// Print the sorted order

for(i=0; i<k; i++)

{

System.out.print(arr3[i] + “ “);

}

System.out.println();

}

}

Java program

Java Program for BinarySearch

Java program for Selection Sort

Loops in Java — Java loop explained with examples

Java for loop

Array in Java

Twin prime number in java

circular prime number program in java

Java program for Pronic Number

Java program for Evil Number

Java Program to find Emirp Number

Neon number program in java

Java program for Evil Number

JAVA QUESTIONS AND ANSWERS FOR BEGINNERS

Originally published at https://javaknowhow.blogspot.com.

--

--

Khurshid Md Anwar
Khurshid Md Anwar

Written by Khurshid Md Anwar

Computer Science Trainer and blogger

No responses yet