Merging two unsorted arrays in sorted order in C++.

Problem statement

Write a function that takes two unsorted arrays and merges them into a new array in sorted order.

arr1[] = {10, 5, 7, 2}
arr2[] = {4, 17, 9, 3}
result[] = {2, 3, 4, 5, 7, 9, 10, 17}

Algorithm

1. Merge two unsorted array into new array
2. Sort newly create array

Example

#include 
#include 
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
void mergeAndSort(int *arr1, int n1, int *arr2, int n2, int *result){
   merge(arr1, arr1 + n1, arr2, arr2 + n2, result);
   sort(result, result + n1 + n2);
}
void displayArray(int *arr, int n){
   for (int i = 0; i 

Output

When you compile and execute the above program. It generates the following output −

First array:
10 5 7 2
Second array:
10 5 7 2
Merged and sorted array:
2 3 4 5 7 9 10 17
Updated on: 2019-10-31T06:03:10+05:30

512 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements