{"id":25548,"date":"2017-05-30T19:15:23","date_gmt":"2017-05-30T13:45:23","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25548"},"modified":"2018-10-27T19:52:09","modified_gmt":"2018-10-27T14:22:09","slug":"algorithm-in-c-median-of-two-sorted-arrays","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/algorithm-in-c-median-of-two-sorted-arrays\/","title":{"rendered":"Algorithm in C &#8211; Median of two sorted arrays"},"content":{"rendered":"<h2 id=\"median\"><span style=\"color: #ff6600;\">Median<\/span><\/h2>\n<ul>\n<li>\u00a0A <a href=\"https:\/\/www.wikitechy.com\/technology\/java-programming-randomized-algorithms\/\">median<\/a> is described as the number separating the higher half of a sample, a population, or a probability distribution, from the lower half In probability theory and statistics.<\/li>\n<li>The median of a finite list of numbers can be found by arranging all the<a href=\"https:\/\/www.wikitechy.com\/technology\/python-programming-interesting-methode-to-generate-binary-numbers-from-1-to-n\/\"> numbers<\/a> from lowest value to highest value and picking the middle one.<\/li>\n<\/ul>\n<h2 id=\"how-to-find-median-in-arrays\"><span style=\"color: #ff00ff;\">How to Find median in Arrays:<\/span><\/h2>\n<p>For getting the median of input array<\/p>\n<p>let int Arr = { 12, 10, 18, 4, 30 }; first sort the array.<\/p>\n<p>We get { 4, 10, 12, 18, 30 } after sorting.<\/p>\n<p><strong>Median is the middle element of the sorted array i.e. 12<\/strong>.<\/p>\n<p>There are different conventions to take median of an array with even number of elements, one can take the mean of the two middle values, or first middle value, or second middle value.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Let us see different <a href=\"https:\/\/www.wikitechy.com\/technology\/methods-clearfix-can-use\/\">methods<\/a> to get the median of two sorted arrays of size n each. Since size of the set for which we are looking for median is even (2n), we take average of middle two numbers in all below solutions and return floor of the average.<\/p>\n<figure id=\"attachment_31608\" aria-describedby=\"caption-attachment-31608\" style=\"width: 655px\" class=\"wp-caption aligncenter\"><img fetchpriority=\"high\" decoding=\"async\" class=\" wp-image-31608\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Median-of-two-sorted-arrays-1.png\" alt=\"\" width=\"655\" height=\"784\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Median-of-two-sorted-arrays-1.png 715w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Median-of-two-sorted-arrays-1-251x300.png 251w\" sizes=\"(max-width: 655px) 100vw, 655px\" \/><figcaption id=\"caption-attachment-31608\" class=\"wp-caption-text\">Median of two sorted arrays<\/figcaption><\/figure>\n<h2 id=\"practice\"><span id=\"method-1-simply-count-while-merging\"><span style=\"color: #0000ff;\"><strong>Method 1 (Simply count while Merging)<\/strong><\/span><\/span><\/h2>\n<div>Use merge procedure of merge sort. Keep track of count while comparing elements of two <a href=\"https:\/\/www.wikitechy.com\/technology\/cc-programming-maximum-of-all-subarrays-of-size-k\/\">arrays<\/a>. If count becomes n(For 2n elements), we have reached the median. Take the average of the elements at indexes n-1 and n in the merged array.<\/div>\n<div><\/div>\n<div>See the below implementation.<\/div>\n<div><\/div>\n<div><strong>Implementation:<\/strong><\/div>\n<h3 id=\"c-programming\"><strong>C Programming<\/strong><\/h3>\n<div>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ A Simple Merge based O(n) solution to find median of<br\/>\/\/ two sorted arrays<br\/>#include &lt;stdio.h&gt;<br\/> <br\/>\/* This function returns median of ar1[] and ar2[].<br\/>   Assumptions in this function:<br\/>   Both ar1[] and ar2[] are sorted arrays<br\/>   Both have n elements *\/<br\/>int getMedian(int ar1[], int ar2[], int n)<br\/>{<br\/>    int i = 0;  \/* Current index of i\/p array ar1[] *\/<br\/>    int j = 0; \/* Current index of i\/p array ar2[] *\/<br\/>    int count;<br\/>    int m1 = -1, m2 = -1;<br\/> <br\/>    \/* Since there are 2n elements, median will be average<br\/>     of elements at index n-1 and n in the array obtained after<br\/>     merging ar1 and ar2 *\/<br\/>    for (count = 0; count &lt;= n; count++)<br\/>    {<br\/>        \/*Below is to handle case where all elements of ar1[] are<br\/>          smaller than smallest(or first) element of ar2[]*\/<br\/>        if (i == n)<br\/>        {<br\/>            m1 = m2;<br\/>            m2 = ar2[0];<br\/>            break;<br\/>        }<br\/> <br\/>        \/*Below is to handle case where all elements of ar2[] are<br\/>          smaller than smallest(or first) element of ar1[]*\/<br\/>        else if (j == n)<br\/>        {<br\/>            m1 = m2;<br\/>            m2 = ar1[0];<br\/>            break;<br\/>        }<br\/> <br\/>        if (ar1[i] &lt; ar2[j])<br\/>        {<br\/>            m1 = m2;  \/* Store the prev median *\/<br\/>            m2 = ar1[i];<br\/>            i++;<br\/>        }<br\/>        else<br\/>        {<br\/>            m1 = m2;  \/* Store the prev median *\/<br\/>            m2 = ar2[j];<br\/>            j++;<br\/>        }<br\/>    }<br\/> <br\/>    return (m1 + m2)\/2;<br\/>}<br\/> <br\/>\/* Driver program to test above function *\/<br\/>int main()<br\/>{<br\/>    int ar1[] = {1, 12, 15, 26, 38};<br\/>    int ar2[] = {2, 13, 17, 30, 45};<br\/> <br\/>    int n1 = sizeof(ar1)\/sizeof(ar1[0]);<br\/>    int n2 = sizeof(ar2)\/sizeof(ar2[0]);<br\/>    if (n1 == n2)<br\/>        printf(&quot;Median is %d&quot;, getMedian(ar1, ar2, n1));<br\/>    else<br\/>        printf(&quot;Doesn&#039;t work for arrays of unequal size&quot;);<br\/>    getchar();<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output<\/strong><\/p>\n<pre>Median is 16<\/pre>\n<p>Time Complexity: O(n)<\/p>\n[ad type=&#8221;banner&#8221;]\n<\/div>\n<div>\n<div class=\"responsive-tabs-wrapper\">\n<div class=\"responsive-tabs responsive-tabs--enabled\">\n<div id=\"tablist1-panel1\" class=\"tabcontent responsive-tabs__panel responsive-tabs__panel--active\">\n<h2 id=\"method-2-by-comparing-the-medians-of-two-arrays\"><span style=\"color: #008080;\"><strong>Method 2 (By comparing the medians of two arrays)<\/strong><\/span><\/h2>\n<p>This method works by first getting medians of the two <a href=\"https:\/\/www.wikitechy.com\/technology\/intersection-two-sorted-linked-lists\/\">sorted<\/a> arrays and then comparing them.<\/p>\n<p>Let ar1 and ar2 be the input arrays.<\/p>\n<p><strong>Algorithm:<\/strong><\/p>\n<pre>1) Calculate the medians m1 and m2 of the input arrays ar1[] \r\n   and ar2[] respectively.\r\n2) If m1 and m2 both are equal then we are done.\r\n     return m1 (or m2)\r\n3) If m1 is greater than m2, then median is present in one \r\n   of the below two subarrays.\r\n    a)  From first element of ar1 to m1 (ar1[0...|_n\/2_|])\r\n    b)  From m2 to last element of ar2  (ar2[|_n\/2_|...n-1])\r\n4) If m2 is greater than m1, then median is present in one    \r\n   of the below two subarrays.\r\n   a)  From m1 to last element of ar1  (ar1[|_n\/2_|...n-1])\r\n   b)  From first element of ar2 to m2 (ar2[0...|_n\/2_|])\r\n5) Repeat the above process until size of both the subarrays \r\n   becomes 2.\r\n6) If size of the two arrays is 2 then use below formula to get \r\n  the median.\r\n    Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))\/2\r\n<\/pre>\n<p><strong>Example:<\/strong><\/p>\n<pre>   ar1[] = {1, 12, 15, 26, 38}\r\n   ar2[] = {2, 13, 17, 30, 45}\r\n<\/pre>\n<p>For above two arrays m1 = 15 and m2 = 17<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>For the above ar1[] and ar2[], m1 is smaller than m2. So median is present in one of the following two subarrays.<\/p>\n<pre>   [15, 26, 38] and [2, 13, 17]\r\n<\/pre>\n<p>Let us repeat the process for above two <a href=\"https:\/\/www.wikitechy.com\/technology\/cc-programming-maximum-of-all-subarrays-of-size-k\/\">subarrays<\/a>:<\/p>\n<pre>    m1 = 26 m2 = 13.\r\n<\/pre>\n<p>m1 is greater than m2. So the subarrays become<\/p>\n<pre>  [15, 26] and [13, 17]\r\nNow size is 2, so median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))\/2\r\n                       = (max(15, 13) + min(26, 17))\/2 \r\n                       = (15 + 17)\/2\r\n                       = 16<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p><strong>Implementation:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ A divide and conquer based efficient solution to find median<br\/>\/\/ of two sorted arrays of same size.<br\/>#include&lt;bits\/stdc++.h&gt;<br\/>using namespace std;<br\/> <br\/>int median(int [], int); \/* to get median of a sorted array *\/<br\/> <br\/>\/* This function returns median of ar1[] and ar2[].<br\/>   Assumptions in this function:<br\/>   Both ar1[] and ar2[] are sorted arrays<br\/>   Both have n elements *\/<br\/>int getMedian(int ar1[], int ar2[], int n)<br\/>{<br\/>    \/* return -1  for invalid input *\/<br\/>    if (n &lt;= 0)<br\/>        return -1;<br\/>    if (n == 1)<br\/>        return (ar1[0] + ar2[0])\/2;<br\/>    if (n == 2)<br\/>        return (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1])) \/ 2;<br\/> <br\/>    int m1 = median(ar1, n); \/* get the median of the first array *\/<br\/>    int m2 = median(ar2, n); \/* get the median of the second array *\/<br\/> <br\/>    \/* If medians are equal then return either m1 or m2 *\/<br\/>    if (m1 == m2)<br\/>        return m1;<br\/> <br\/>    \/* if m1 &lt; m2 then median must exist in ar1[m1....] and<br\/>        ar2[....m2] *\/<br\/>    if (m1 &lt; m2)<br\/>    {<br\/>        if (n % 2 == 0)<br\/>            return getMedian(ar1 + n\/2 - 1, ar2, n - n\/2 +1);<br\/>        return getMedian(ar1 + n\/2, ar2, n - n\/2);<br\/>    }<br\/> <br\/>    \/* if m1 &gt; m2 then median must exist in ar1[....m1] and<br\/>        ar2[m2...] *\/<br\/>    if (n % 2 == 0)<br\/>        return getMedian(ar2 + n\/2 - 1, ar1, n - n\/2 + 1);<br\/>    return getMedian(ar2 + n\/2, ar1, n - n\/2);<br\/>}<br\/> <br\/>\/* Function to get median of a sorted array *\/<br\/>int median(int arr[], int n)<br\/>{<br\/>    if (n%2 == 0)<br\/>        return (arr[n\/2] + arr[n\/2-1])\/2;<br\/>    else<br\/>        return arr[n\/2];<br\/>}<br\/> <br\/>\/* Driver program to test above function *\/<br\/>int main()<br\/>{<br\/>    int ar1[] = {1, 2, 3, 6};<br\/>    int ar2[] = {4, 6, 8, 10};<br\/>    int n1 = sizeof(ar1)\/sizeof(ar1[0]);<br\/>    int n2 = sizeof(ar2)\/sizeof(ar2[0]);<br\/>    if (n1 == n2)<br\/>        printf(&quot;Median is %d&quot;, getMedian(ar1, ar2, n1));<br\/>    else<br\/>        printf(&quot;Doesn&#039;t work for arrays of unequal size&quot;);<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output :<\/strong><\/p>\n<pre>Median is 5<\/pre>\n<p>Time Complexity: O(logn)<\/p>\n<p>Algorithmic Paradigm: Divide and Conquer<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Divide and Conquer &#8211; Median of two sorted arrays There are 2 sorted arrays A and B of size n each. Write an algorithm to find the median of the array.<\/p>\n","protected":false},"author":1,"featured_media":26080,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73719],"tags":[74218,73619,74227,72903,74211,74223,74221,74230,74212,74228,74229,72915,74225,74224,74226,74214,74213,74215,74217,74219,74220,74216,74222],"class_list":["post-25548","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-divide-and-conquer","tag-algorithm-to-merge-two-sorted-arrays","tag-c-program-to-merge-two-sorted-arrays","tag-find-kth-element-in-two-sorted-arrays","tag-find-kth-smallest-element-in-two-sorted-arrays","tag-find-median-of-two-sorted-arrays","tag-find-median-of-two-sorted-arrays-java","tag-java-program-to-merge-two-sorted","tag-matrix-median-leetcode","tag-median-of-2-sorted-arrays","tag-median-of-k-sorted-arrays","tag-median-of-sorted-array-java","tag-median-of-two-sorted-arrays","tag-median-of-two-sorted-arrays-binary-search","tag-median-of-two-sorted-arrays-of-different-sizes","tag-median-of-two-sorted-arrays-python","tag-merge-2-sorted-arrays","tag-merge-two-sorted-arrays","tag-merge-two-sorted-arrays-in-c","tag-merge-two-sorted-arrays-in-java","tag-merge-two-sorted-arrays-into-one-sorted-array-in-java","tag-merging-of-two-sorted-arrays","tag-sorted-arrays","tag-write-a-program-to-merge-two-sorted-arrays"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25548","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25548"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25548\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/26080"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25548"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25548"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25548"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}