Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Median of two sorted array
Medians are the middle numbers, in other words, the median value is the middle observation in an ordered list. It corresponds to the cumulative percentage of 50%.
The size of two arrays must be same, we will find the median of two separate arrays at first, then compare the separate medians to get an actual median of two lists.
Input and Output
Input:
Two sorted array are given.
Array 1: {1, 2, 3, 6, 7}
Array 2: {4, 6, 8, 10, 11}
Output:
The median from two array. Here the median value is 6.
Merge the given lists into one. {1, 2, 3, 4, 6, 6, 7, 8, 10, 11}
From the merged list find the average of two middle elements. here (6+6)/2 = 6.
Algorithm
median(list, n)
Input: List of data, and the number of data.
Output: Median of the given list.
Begin if the list has even number of data, then return (list[n/2] + list[n/2-1])/2 else return list[n/2] End
findMedian(list1, list2, n)
Input − Two sorted lists, and the number of lists.
Output − The median from two sorted lists.
Begin if nExample
#includeusing namespace std; int median(int list[], int n) { if (n%2 == 0) //when array containts even number of data return (list[n/2] + list[n/2-1])/2; else //for odd number of data return list[n/2]; } intfindMedian(int list1[], int list2[], int n) { if (n med2 return findMedian(list2 + n/2 - 1, list1, n - n/2 + 1); return findMedian(list2 + n/2, list1, n - n/2); } int main() { int list1[] = {1, 2, 3, 6, 7}; int list2[] = {4, 6, 8, 10, 11}; int n1 = 5; int n2 = 5; if (n1 == n2) cout Output
Median is 6
Advertisements
