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 Java, and 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.

E.t.c.

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




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.



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.

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