Merging two unsorted arrays in sorted order (original) (raw)
Last Updated : 31 Jul, 2025
Given two integer arrays **arr1[] and **arr2[], merge them into a single array such that the resulting array contains only unique elements from both arrays. Additionally, the final array should be sorted in ascending order.
**Examples :
**Input: arr1[] = [11, 1, 8], arr2[] = [10, 11]
**Output: [1, 8, 10, 11]
**Explanation: The ouput array after merging both the arrays and removing duplicates is [1 8, 10, 11].**Input: arr1[] = [7, 1, 5, 3, 9], arr2[] = [8, 4, 3, 5, 2, 6]
**Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
**Explanation: The ouput array after merging both the arrays and removing duplicates is [1, 2, 3, 4, 5, 6, 7, 8, 9].
Table of Content
[Approach 1] First concatenate then sort
The idea is to merge two unsorted arrays into a single list, then sort that list and remove any duplicate elements to get a sorted arrays of unique values.
C++ `
#include #include #include using namespace std;
vector mergeNsort(vector& arr1, vector& arr2) { vector res; int i = 0, j = 0;
// Push elements of 'arr1' into res
while (i < arr1.size()) {
res.push_back(arr1[i]);
i++;
}
// Push elements of 'arr2' into res
while (j < arr2.size()) {
res.push_back(arr2[j]);
j++;
}
// Sort the merged vector
sort(res.begin(), res.end());
// Remove duplicates (unique elements only)
res.erase(unique(res.begin(), res.end()), res.end());
return res;}
int main() { vector arr1 = {11, 1, 8}; vector arr2 = {10, 11};
vector<int> res = mergeNsort(arr1, arr2);
for (int x : res)
cout << x << " ";
return 0;}
Java
import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections;
public class GfG {
static ArrayList<Integer> mergeNsort(int[] arr1, int[] arr2) {
ArrayList<Integer> res = new ArrayList<>();
int i = 0, j = 0;
// Push elements of 'arr1' into res
while (i < arr1.length) {
res.add(arr1[i]);
i++;
}
// Push elements of 'arr2' into res
while (j < arr2.length) {
res.add(arr2[j]);
j++;
}
// Sort the merged list
Collections.sort(res);
// Remove duplicates (unique elements only)
ArrayList<Integer> uniqueRes = new ArrayList<>();
for (int val : res) {
if (uniqueRes.isEmpty() || uniqueRes.get(uniqueRes.size() - 1) != val) {
uniqueRes.add(val);
}
}
return uniqueRes;
}
public static void main(String[] args) {
int[] arr1 = {11, 1, 8};
int[] arr2 = {10, 11};
ArrayList<Integer> res = mergeNsort(arr1, arr2);
for (int x : res)
System.out.print(x + " ");
}}
Python
def mergeNsort(arr1, arr2): res = []
i = 0
j = 0
# Push elements of 'arr1' into res
while i < len(arr1):
res.append(arr1[i])
i += 1
# Push elements of 'arr2' into res
while j < len(arr2):
res.append(arr2[j])
j += 1
# Sort and remove duplicates
res = sorted(set(res))
return resif name == "main": arr1 = [11, 1, 8] arr2 = [10, 11]
res = mergeNsort(arr1, arr2)
for x in res:
print(x, end=" ")C#
using System; using System.Collections.Generic;
class GfG { static List mergeNsort(int[] arr1, int[] arr2) { List res = new List();
int i = 0, j = 0;
// Push elements of 'arr1' into res
while (i < arr1.Length)
{
res.Add(arr1[i]);
i++;
}
// Push elements of 'arr2' into res
while (j < arr2.Length)
{
res.Add(arr2[j]);
j++;
}
// Sort the merged list
res.Sort();
// Remove duplicates (unique elements only)
List<int> uniqueRes = new List<int>();
foreach (int val in res)
{
if (uniqueRes.Count == 0 || uniqueRes[uniqueRes.Count - 1] != val)
{
uniqueRes.Add(val);
}
}
return uniqueRes;
}
static void Main()
{
int[] arr1 = { 11, 1, 8 };
int[] arr2 = { 10, 11 };
List<int> res = mergeNsort(arr1, arr2);
foreach (int x in res)
Console.Write(x + " ");
}}
JavaScript
function mergeNsort(arr1, arr2) { let res = []; let i = 0, j = 0;
// Push elements of 'arr1' into res
while (i < arr1.length) {
res.push(arr1[i]);
i++ ;
}
// Push elements of 'arr2' into res
while (j < arr2.length) {
res.push(arr2[j]);
j++;
}
// Sort and remove duplicates
res.sort((x, y) => x - y);
let uniqueRes = [];
for (let val of res) {
if (uniqueRes.length === 0 || uniqueRes[uniqueRes.length - 1] !== val) {
uniqueRes.push(val);
}
}
return uniqueRes;}
// Driver Code let arr1 = [11, 1, 8]; let arr2 = [10, 11]; let res = mergeNsort(arr1, arr2); console.log(res.join(" "));
`
**Time Complexity: O((n + m)*log(n + m))
**Auxiliary Space: O(n + m)
[Approach 2] First sort then merge
First, sorts both input arrays individually. Then, merge them into a result array by comparing elements one by one from both sorted arrays, maintaining the overall sorted order. Any remaining elements from either array are appended after one finishes.
C++ `
#include #include #include using namespace std;
vector mergeNsort(vector& arr1, vector& arr2) {
// Sort both arrays
sort(arr1.begin(), arr1.end());
sort(arr2.begin(), arr2.end());
vector<int> res;
int i = 0, j = 0;
// Merge two sorted arrays into res
// (unique check inside loop)
while (i < arr1.size() && j < arr2.size()) {
int val;
if (arr1[i] <= arr2[j]) {
val = arr1[i++];
} else {
val = arr2[j++];
}
if (res.empty() || res.back() != val)
res.push_back(val);
}
// Merge remaining elements from a[]
while (i < arr1.size()) {
if (res.empty() || res.back() != arr1[i])
res.push_back(arr1[i]);
i++;
}
// Merge remaining elements from b[]
while (j < arr2.size()) {
if (res.empty() || res.back() != arr2[j])
res.push_back(arr2[j]);
j++;
}
return res;}
int main() { vector arr1 = {11, 1, 8}; vector arr2 = {10, 11};
vector<int> res = mergeNsort(arr1, arr2);
for (int x : res)
cout << " " << x;
return 0;}
Java
import java.util.List; import java.util.ArrayList; import java.util.Arrays;
class GfG {
static ArrayList<Integer> mergeNsort(int[] arr1, int[] arr2) {
Arrays.sort(arr1);
Arrays.sort(arr2);
ArrayList<Integer> res = new ArrayList<>();
int i = 0, j = 0;
// Merge two sorted arrays (unique check inside loop)
while (i < arr1.length && j < arr2.length) {
int val;
if (arr1[i] <= arr2[j]) {
val = arr1[i++];
} else {
val = arr2[j++];
}
if (res.isEmpty() || res.get(res.size() - 1) != val)
res.add(val);
}
// Remaining elements from a[]
while (i < arr1.length) {
if (res.isEmpty() || res.get(res.size() - 1) != arr1[i])
res.add(arr1[i]);
i++;
}
// Remaining elements from b[]
while (j < arr2.length) {
if (res.isEmpty() || res.get(res.size() - 1) != arr2[j])
res.add(arr2[j]);
j++;
}
return res;
}
public static void main(String[] args) {
int[] arr1 = {11, 1, 8};
int[] arr2 = {10, 11};
ArrayList<Integer> res = mergeNsort(arr1, arr2);
for (int x : res)
System.out.print(x + " ");
}}
Python
def mergeNsort(arr1, arr2): arr1.sort() arr2.sort()
res = []
i = j = 0
# Merge two sorted lists (unique check inside loop)
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j]:
val = arr1[i]
i += 1
else:
val = arr2[j]
j += 1
if not res or res[-1] != val:
res.append(val)
# Remaining elements from a[]
while i < len(arr1):
if not res or res[-1] != arr1[i]:
res.append(arr1[i])
i += 1
# Remaining elements from arr2[]
while j < len(arr2):
if not res or res[-1] != arr2[j]:
res.append(arr2[j])
j += 1
return resif name == "main": arr1 = [11, 1, 8] arr2 = [10, 11]
res = mergeNsort(arr1, arr2)
print(" ".join(map(str, res)))C#
using System; using System.Collections.Generic;
class GfG { static List mergeNsort(int[] arr1, int[] arr2) { Array.Sort(arr1); Array.Sort(arr2);
List<int> res = new List<int>();
int i = 0, j = 0;
// Merge two sorted arrays (unique check inside loop)
while (i < arr1.Length && j < arr2.Length) {
int val;
if (arr1[i] <= arr2[j]) {
val = arr1[i++];
}
else {
val = arr2[j++];
}
if (res.Count == 0 || res[res.Count - 1] != val)
res.Add(val);
}
// Remaining elements from a[]
while (i < arr1.Length)
{
if (res.Count == 0 || res[res.Count - 1] != arr1[i])
res.Add(arr1[i]);
i++;
}
// Remaining elements from arr2[]
while (j < arr2.Length)
{
if (res.Count == 0 || res[res.Count - 1] != arr2[j])
res.Add(arr2[j]);
j++;
}
return res;
}
static void Main()
{
int[] arr1 = { 11, 1, 8 };
int[] arr2 = { 10, 11 };
List<int> res = mergeNsort(arr1, arr2);
foreach (int x in res)
Console.Write(x + " ");
}}
JavaScript
function mergeNsort(arr1, arr2) { arr1.sort((x, y) => x - y); arr2.sort((x, y) => x - y);
let res = [];
let i = 0, j = 0;
// Merge two sorted arrays (unique check inside loop)
while (i < arr1.length && j < arr2.length) {
let val;
if (arr1[i] <= arr2[j]) {
val = arr1[i++];
} else {
val = arr2[j++];
}
if (res.length === 0 || res[res.length - 1] !== val)
res.push(val);
}
// Remaining elements from arr1[]
while (i < arr1.length) {
if (res.length === 0 || res[res.length - 1] !== arr1[i])
res.push(arr1[i]);
i++;
}
// Remaining elements from arr2[]
while (j < arr2.length) {
if (res.length === 0 || res[res.length - 1] !== arr2[j])
res.push(arr2[j]);
j++;
}
return res;}
// Driver Code let arr1 = [11, 1, 8]; let arr2 = [10, 11];
let res = mergeNsort(arr1, arr2); console.log(res.join(" "));
`
**Time Complexity: O(nlog(n) + mlog(m))
**Auxiliary **Space: O(1)