
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
C/C++ Program for Median of two sorted arrays of same size?
Here we will see how to get the median of two sorted array of the same size. We will use C++ STL to store array elements. After getting two arrays, we will merge them into one. As two arrays of same size are merged, then the final array will always hold even number of elements. We need to take two middle elements, then get the average of them for the median.
Algorithm
median(arr1, arr2)
Begin arr3 := array after merging arr1 and arr2 sort arr3 len := length of arr3 mid := len/2 median := (arr3[mid] + arr3[mid-1])/2 return median End
Example
#include<iostream> #include<vector> #include<algorithm> using namespace std; float median(vector<int> arr1, vector<int> arr2) { vector arr3(arr1.size() + arr2.size()); merge(arr1.begin(), arr1.end(), arr2.begin(), arr2.end(), arr3.begin()); sort(arr3.begin(), arr3.end()); int len = arr3.size(); int mid = len/2; return float(arr3[mid] + arr3[mid-1])/2; } main() { vector<int> arr1 = {1, 3, 4, 6, 7}; vector<int> arr2 = {4, 5, 7, 8, 9}; cout << "Median: " << median(arr1, arr2); }
Output
Median: 5.5
- Related Articles
- Median of Two Sorted Arrays in C++
- C++ Program to find the median of two sorted arrays using binary search approach
- Program to find median of two sorted lists in C++
- Median of two sorted array
- How to quickly swap two arrays of the same size in C++?
- JavaScript Program for find common elements in two sorted arrays
- C# program to merge two sorted arrays into one
- Find relative complement of two sorted arrays in C++
- K-th Element of Two Sorted Arrays in C++
- Python Program for Find the closest pair from two sorted arrays
- Merge two sorted arrays using C++.
- Merge two sorted arrays in C#
- Java program to create a sorted merged array of two unsorted arrays
- Intersection of Three Sorted Arrays in C++
- Merging two unsorted arrays in sorted order in C++.

Advertisements