Disclosure: This article may contain affiliate links. When you purchase, we may earn a small commission.

How to Merge sorted array in Java? Example Tutorial

Hello guys, if you want to learn how to merge two sorted arrays in Java then you have come to the right place. Earlier, I have shown you how to sort arrays in Javaand in this article, I will show you how to merge two sorted arrays in Java. Btw, if you are a complete beginner then Firstly, you need to know what an array is before going about solving a task around it. What then is an Array? An array is a data structure in java that holds values of the same type with its length specified right from creation time. Think of a container, like a crate of eggs or coke.


What I am trying to say is that when you are creating your array, the items coming in must be the same and you must specify how many items are coming. If you have stated that the items coming are integers, so it is and no other data type (e.g string, char e.t.c) can be there and vice versa.

How do you create an array?
  1. Int [] num = new int [5];

In this previous line of code, you are creating an array of integer numbers with the variable name "num" and you are assigning it to a new integer of length 5. meaning that the items coming can only be an integer and it has to be 5. anything that does not correlate with what you have specified results to compilation error.

In an array you can access each element through its index, the index number starts from zero. So the element 1 is index num 0,2 is index num 1, 3 is index num 3, and on and on as you can see above.

If you want to get the total number of the index you will do length - 1 because the length you specified at creation time is 5 and because the indexes start from 0, not 1. so, the length of the indexes is 4.




Array Methods in java.

There are methods readily available in java arrays which you can call to use at anytime
  • Arrays.toString() : This method prints an array
  • Arrays.asList(): This method takes an array and converts it to list
  • Arrays.sort(): This method sorts an array.
  • Arrays.compare(): This method compares two different arrays.
  • Arrays.fill(): This method populates an empty array with the items you put in the method.
  • Arrays.equals(): This method checks if two arrays are equal.
  • Arrays.copyOf(): This method makes another copy of the same array you use this method on.

By now should know what arrays look like, in our tutorial today we would be solving how to merge sorted arrays. Imagine two different class arrays that need to be sorted first. After sorting them differently, you would have to merge them.

This article will not let you know how to merge alone but how to get the array sorted first since it is a sorted array we want to merge. So, whether the two arrays are sorted or not, the code implementation handles it, meaning that if the array is not sorted and was passed into the parameter, it sorts it.

Let us check the codes and explanation.



Java Program to sort and Merge Array

Here is our complete Java program to first sort the array and then merge them.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class Task {
    public static Integer[] mergeArrayInAscendingOrder(int[] classA, int[] classB) {
        //merge two Arrays
        List < Integer > myList = new ArrayList < > ();
        for (int i: classA) {
            myList.add(i);
        }
        for (int j: classB) {
            myList.add(j);
        }
        Integer[] newArray = new Integer[myList.size()];
        myList.toArray(newArray);
        //sort them in ascending order
        for (int i = 0; i < newArray.length; i++) {
            for (int j = i; j < newArray.length; j++) {
                Integer temp = newArray[i];
                if (newArray[i] > newArray[j]) {
                    newArray[i] = newArray[j];
                    newArray[j] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(newArray));
        return newArray;
    }
    public static void main(String[] args) {
        int[] classA = {
            4,
            2,
            9
        };
        int[] classB = {
            6,
            7,
            8
        };
        mergeArrayInAscendingOrder(classA, classB);
    }
}





EXPLANATION

Line one is the class declaration and line 2 created the method that merges the two-class array which of course takes in two unsorted class arrays as parameters pf type int, class A and class B respectively.

Line 4 initiated a list of Integers of variable myList. Line 5 is a loop that traverses through class A and adds each item in class A into the list that was just created. And the same thing to class B in line 8 and line 9.

Line 11 creates a new array where the new set of values would be stored after merging whose length is the size of the list. Line 10 converts the list to array and line 14 handles the arrays if not sorted when being passed to the parameter.

How to Merge sorted array in Java? Example Tutorial
Fig 1.0: Merging arrays.


For loops runs in line 14 and line 15 and a temporary variable “temp” was created to temporarily hold value in line 16 and the value is array at index i. If the array at index i is greater than the array at index j, then newArray at index j should be assigned to newArray at index i, and the array at index j should now point to temp.

newArray was returned in line 24. The main method starts in line 26 and values were added into class A and B respectively, then the method was called with the classes as arguments.

Other Java Array Tutorials and Examples you may like:
  • How to check if two String array are equals in Java? (solution)
  • 20+ String Coding Problems from Interviews (questions)
  • How to remove duplicates from an unsorted array in Java? (solution)
  • 20+ array-based coding problems from Interviews (Questions)
  • The ultimate guide of arrays in Java (tutorial)
  • 22 Array Concepts Interview Questions in Java (questions)
  • How to create an array from ArrayList of String in Java (tutorial)
  • 7 Best Courses to learn Data Structure and Algorithms (courses)
  • 10 Data Structure Courses to Crack Programming Interviews (courses)
  • 20+ binary tree-based coding problems (questions)
  • Top 20 Searching and Sorting Interview Questions (questions)
  • How to make a binary search tree in Java? (solution)
  • How to find all pairs whose sum is equal to a given number in an array? (solution)
  • How to reverse an array in place in Java? (solution)
  • 10 Algorithms Books Every Programmer Should Read (books)
  • 10 Free Data Structure and Algorithm Courses for Beginners (courses)
  • 50+ Data Structure and Algorithms Interview Questions (questions)

Thanks for reading this article so far. If you like this how to merge sorted array in Java problem and my solution and explanation then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are looking to learn Data Structure and Algorithms from scratch or want to fill gaps in your understanding and looking for some free courses, then you can check out this list of Free Algorithms Courses to start with.

1 comment :

Anonymous said...

This example works but it should never been used in real program.
1. Data are in memory three times (orig. arrays, List, target array).
2. Bubble sort (I know, the orig. arrays are sorted, but no thanks).
3. The temp property in line 16 can be moved to if body.

Post a Comment