w3resource

Java Array Exercises: Merge elements of A with B by maintaining the sorted order

Java Array: Exercise-58 with Solution

Given two sorted arrays A and B of size p and q, write a Java program to merge elements of A with B by maintaining the sorted order i.e. fill A with first p smallest elements and fill B with remaining elements.

Example:
Input :
int[] A = { 1, 5, 6, 7, 8, 10 }
int[] B = { 2, 4, 9 }
Output:
Sorted Arrays:
A: [1, 2, 4, 5, 6, 7]
B: [8, 9, 10]

Sample Solution:

Java Code:

import java.util.Arrays;

class solution
{
	public static void merge_sorted_arrays(int[] A, int p, int[] B, int q)
	{
		
		for (int i = 0; i < p; i++)
		{
			if (A[i] > B[0])
			{
				int temp = A[i];
				A[i] = B[0];
				B[0] = temp;

				int first_arr = B[0];
				int k;
				for (k = 1; k < q && B[k] < first_arr; k++) {
					B[k - 1] = B[k];
				}

				B[k - 1] = first_arr;
			}
		}
	}

	public static void main (String[] args)
	{
		int[] A = { 1, 5, 6, 7, 8, 10 };
		int[] B = { 2, 4, 9 };
		int p = A.length;
		int q = B.length;

		System.out.println("Original Arrays:");
		System.out.println("A: " + Arrays.toString(A));
		System.out.println("B: " + Arrays.toString(B));
		
		merge_sorted_arrays(A, p, B, q);
        
		System.out.println("\nSorted Arrays:");
		System.out.println("A: " + Arrays.toString(A));
		System.out.println("B: " + Arrays.toString(B));
	}
}

Sample Output:

Original Arrays:
A: [1, 5, 6, 7, 8, 10]
B: [2, 4, 9]

Sorted Arrays:
A: [1, 2, 4, 5, 6, 7]
B: [8, 9, 10]

Flowchart:

Flowchart: Merge elements of A with B by maintaining the sorted order

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to check if a sub-array is formed by consecutive integers from a given array of integers.
Next: Write a Java program to find maximum product of two integers in a given array of integers.

What is the difficulty level of this exercise?



Java: Tips of the Day

Different between parseInt() and valueOf() in java?

Well, the API for Integer.valueOf(String) does indeed say that the String is interpreted exactly as if it were given to Integer.parseInt(String). However, valueOf(String) returns a new Integer() object whereas parseInt(String) returns a primitive int.

If you want to enjoy the potential caching benefits of Integer.valueOf(int), you could also use this eyesore:

Integer k = Integer.valueOf(Integer.parseInt("123"))

Now, if what you want is the object and not the primitive, then using valueOf(String) may be more attractive than making a new object out of parseInt(String) because the former is consistently present across Integer, Long, Double, etc.

Ref: https://bit.ly/3vRuIPY