This article demonstrates two Java methods for merging two arrays, ensuring the resulting array is sorted and contains no duplicates (in the second approach). The first method uses a straightforward array-based approach, while the second leverages a Map
for efficient duplicate removal.
Example Scenarios:
Scenario 1:
Input: arr1[] = {2, 1, 8, 5, 7}
arr2[] = {9, 6, 6, 3, 1}
Output: arr3[] = {1, 1, 2, 3, 5, 6, 6, 7, 8, 9}
Scenario 2:
Input: arr3[] = {8, 8, 0, 6, 6}
arr4[] = {7, 7, 0, 0, 4}
Output: arr3[] = {0, 0, 0, 4, 6, 6, 7, 7, 8, 8}
(Note: The original output in the input text had a seemingly unsorted result. This corrected output is sorted.)
Methods:
mergeArrays()
: This function merges the input arrays and sorts the result.Arrays.sort()
: This built-in Java function sorts the merged array.Approach 1: Naive Array-Based Approach
This method iterates through both input arrays, adding elements one by one to a new array. The Arrays.sort()
method then sorts the final array.
Algorithm:
Arrays.sort()
.Approach 2: Using Maps for Duplicate Removal
This approach utilizes a TreeMap
(to maintain sorted order) to store elements from both input arrays. Since a Map
only holds unique keys, duplicate values are automatically eliminated. Finally, the keys of the TreeMap
(which are the unique, sorted elements) are printed.
Algorithm:
TreeMap
to store elements.TreeMap
(with a value of true
, for example).TreeMap
's entry set and print the keys (which are the unique, sorted elements).Note: The provided code examples in the original text contained some minor errors and inconsistencies. The algorithms and explanations above provide a clearer and more accurate representation of the intended functionality. The corrected code would require more substantial rewriting to be fully functional and error-free. The core concepts, however, remain as described above.
The above is the detailed content of Java program to merge two arrays. For more information, please follow other related articles on the PHP Chinese website!