
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 <iostream> #include <algorithm> #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 < n; ++i) { cout << arr[i] << " "; } cout << endl; } int main(){ int arr1[] = {10, 5, 7, 2}; int arr2[] = {4, 17, 9, 3}; int result[SIZE(arr1) + SIZE(arr2)]; cout << "First array: " << endl; displayArray(arr1, SIZE(arr1)); cout << "Second array: " << endl; displayArray(arr1, SIZE(arr2)); mergeAndSort(arr1, SIZE(arr1), arr2, SIZE(arr2), result); cout << "Merged and sorted array: " << endl; displayArray(result, SIZE(arr1) + SIZE(arr2)); return 0; }
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
- Related Articles
- Merging two sorted arrays into one sorted array using JavaScript
- Merging sorted arrays together JavaScript
- Quickly merging two sorted arrays using std::merge() in C++ STL(cute ho ap)
- Java program to create a sorted merged array of two unsorted arrays
- Alternatively merging two arrays - JavaScript
- Merging two arrays in a unique way in JavaScript
- Merging Arrays in Perl
- Merge two sorted arrays in Java
- Merge two sorted arrays in C#
- Find Union and Intersection of two unsorted arrays in C++
- Median of Two Sorted Arrays in C++
- Merging elements of two different arrays alternatively in third array in C++.
- Merging and rectifying arrays in JavaScript
- Merge two sorted arrays in Python using heapq?
- Merge two sorted arrays to form a resultant sorted array in JavaScript

Advertisements