In this article, we will discuss how to merge two arrays and then sort according to natural order i.e.; ascending order. Well, by passing Comparator object we can sort in reverse order as well.
Sorting Arrays after merging 2 Arrays :
Steps:
- Create Array 1 with String values {“Sachin”, “Dravid”, “Ganguly”, “Laxman”, “Sehwag”}
- Create Array 2 with String values {“Kumble”, “Srinath”, “Prasad”, “Zaheer”}
- Create third array of size, by adding size of 1st array and 2nd array
- Assign values from String[] array 1 to new third array while iterating 1st array (0-s1)
- Similarly, assign values from String[] array 2 to new third array while iterating 2nd array(s1 – s2)
- Then finally invoke Arrays.sort(mergedArray); on the merged array for sorting merged elements in ascending order
MergeAndSortStringArray.java
package in.bench.resources.java.arrays.sorting; import java.util.Arrays; public class MergeAndSortStringArray { public static void main(String[] args) { // sample String[] array String[] strArray1 = { "Sachin", "Dravid", "Ganguly", "Laxman", "Sehwag" }; String[] strArray2 = { "Kumble", "Srinath", "Prasad", "Zaheer" }; // create another String[] array of size = arr1 + arr2 String[] thirdArray = new String[strArray1.length + strArray2.length]; // iterate through 1st strArray1 and // assign values to thridArray for(int index = 0; index < strArray1.length; index++) { thirdArray[index] = strArray1[index]; } // iterate through 2nd strArray2 and // assign values to thridArray for(int index = strArray1.length, i=0; index < strArray1.length + strArray2.length; index++, i++) { thirdArray[index] = strArray2[i]; } // sorting MERGED String[] array in ascending-order Arrays.sort(thirdArray); // after sorting System.out.println("Sorting merged array : \n"); for(String str : thirdArray) { System.out.println(str); } } }
Output:
Sorting merged array : Dravid Ganguly Kumble Laxman Prasad Sachin Sehwag Srinath Zaheer
Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.
References:
- https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
- https://docs.oracle.com/javase/tutorial/java/data/strings.html
- https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
- https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Happy Coding !!
Happy Learning !!