Merging of two sorted arrays into a third array

Note : Below is not a good example, just a solution that I came up with there could be n number of solutions that are better

Tips

  • Write the code in array list first so that you need not worry about ArrayIndexOutof bond exception rather than handling it

Example with ArrayList :

package com.demo2;

import java.util.ArrayList;
import java.util.List;

public class Example1 {
	public static void main(String[] args) {

		int[] a = { 1, 2, 5, 7 };
		int[] b = { 3, 6, 9, 11 };

		int x = 0, y = 0;

		List<Integer> c = new ArrayList<>();
		int tempLength;
		int tempIterated = 0;
		while (x < a.length) {
			tempLength = c.size();
			y = tempIterated;
			while (y < b.length) {

				if (a[x] < b[y]) {
					c.add(a[x]);
					tempIterated = y;
					break;
				} else {
					c.add(b[y]);
				}
				y++;
			}
			x++;
			if (a.length == x &amp;&amp; c.size() != a.length + b.length) {
				int location = c.size();
				int bLocation = a.length + b.length - c.size();
				while (location < b.length + a.length) {
					c.add(b[bLocation]);
					location++;
					bLocation++;
				}

			}
		}
		c.forEach(System.out::println);
	}
}

Example with Array :

package com.demo2;

import java.util.Arrays;

public class Example2{
	public static void main(String[] args) {

		int[] a = { 1, 2, 5, 7 };
		int[] b = { 3, 6, 9, 11 };

		Integer x = 0, y = 0;

		int[] c = new int[a.length+b.length];
		int tempIterated = 0;
		int cCounter=0;
		
		while (x < a.length) {
			y = tempIterated;
			while (y < b.length) {

				if (a[x] < b[y]) {
					c[cCounter++]=a[x];
					tempIterated = y;
					break;
				} else {
					c[cCounter++] = b[y];
				}
				y++;
			}
			x++;
			int nonNullElements = (int)Arrays.stream(c).filter(intX->intX!=0).count();
			if (a.length == x &amp;&amp; nonNullElements != a.length + b.length) {
				int location = nonNullElements;
				int bLocation = a.length + b.length - nonNullElements;
				while (location < b.length + a.length) {
					c[location]=b[bLocation];
					location++;
					bLocation++;
				}

			}
		}
		Arrays.stream(c).forEach(System.out::println);
	}
}

Note if can even optimize the above code if you take the outer array as the array which as the highest value at the last

Leave a Comment