

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Median of Two Sorted Arrays in C++
- Median of two sorted array
- C++ Program to find the median of two sorted arrays using binary search approach
- Program to find median of two sorted lists in C++
- How to quickly swap two arrays of the same size in C++?
- Find relative complement of two sorted arrays in C++
- K-th Element of Two Sorted Arrays in C++
- JavaScript Program for find common elements in two sorted arrays
- Merge two sorted arrays in C#
- Merge two sorted arrays using C++.
- C# program to merge two sorted arrays into one
- Python Program for Find the closest pair from two sorted arrays
- Java program to create a sorted merged array of two unsorted arrays
- Intersection of Three Sorted Arrays in C++
- Merge two sorted arrays in Java
Advertisements