{"id":25316,"date":"2017-10-15T17:04:50","date_gmt":"2017-10-15T11:34:50","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25316"},"modified":"2017-10-15T17:04:50","modified_gmt":"2017-10-15T11:34:50","slug":"find-closest-pair-two-sorted-arrays","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/find-closest-pair-two-sorted-arrays\/","title":{"rendered":"JAVA programming-Find the closest pair from two sorted arrays"},"content":{"rendered":"<p>Given two sorted arrays and a number x, find the pair whose sum is closest to x and <strong>the pair has an element from each array<\/strong>.<span id=\"more-132487\"><\/span><\/p>\n<p>We are given two arrays ar1[0\u2026m-1] and ar2[0..n-1] and a number x, we need to find the pair ar1[i] + ar2[j] such that absolute value of (ar1[i] + ar2[j] \u2013 x) is minimum.<\/p>\n<p>Example:<\/p>\n<pre>Input:  ar1[] = {1, 4, 5, 7};\r\n        ar2[] = {10, 20, 30, 40};\r\n        x = 32      \r\nOutput:  1 and 30\r\n\r\nInput:  ar1[] = {1, 4, 5, 7};\r\n        ar2[] = {10, 20, 30, 40};\r\n        x = 50      \r\nOutput:  7 and 40\r\n<\/pre>\n<p><strong>We strongly recommend to minimize your browser and try this yourself first.<\/strong><\/p>\n<p>A <strong>Simple Solution<\/strong> is to run two loops. The outer loop considers every element of first array and inner loop checks for the pair in second array. We keep track of minimum difference between ar1[i] + ar2[j] and x.<\/p>\n<p>We can do it <strong>in O(n) time <\/strong>using following steps.<br \/>\n1) Merge given two arrays into an auxiliary array of size m+n using <a href=\"http:\/\/geeksquiz.com\/merge-sort\/\" target=\"_blank\" rel=\"noopener noreferrer\">merge process of merge sort<\/a>. While merging keep another boolean array of size m+n to indicate whether the current element in merged array is from ar1[] or ar2[].<\/p>\n<p>2) Consider the merged array and use the <a href=\"http:\/\/geeksquiz.com\/given-sorted-array-number-x-find-pair-array-whose-sum-closest-x\/\" target=\"_blank\" rel=\"noopener noreferrer\">linear time algorithm to find the pair with sum closest to x<\/a>. One extra thing we need to consider only those pairs which have one element from ar1[] and other from ar2[], we use the boolean array for this purpose.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Can we do it in a single pass and O(1) extra space?<\/strong><br \/>\nThe idea is to start from left side of one array and right side of another array, and use the algorithm same as step 2 of above approach. Following is detailed algorithm.<\/p>\n<pre>1) Initialize a variable diff as infinite (Diff is used to store the \r\n   difference between pair and x).  We need to find the minimum diff.\r\n2) Initialize two index variables l and r in the given sorted array.\r\n       (a) Initialize first to the leftmost index in ar1:  l = 0\r\n       (b) Initialize second  the rightmost index in ar2:  r = n-1\r\n3) Loop while l &lt; m and r &gt;= 0\r\n       (a) If  abs(ar1[l] + ar2[r] - sum) &lt; diff  then \r\n           update diff and result \r\n       (b) Else if(ar1[l] + ar2[r] &lt;  sum )  then l++\r\n       (c) Else r--    \r\n4) Print the result.<\/pre>\n<p>Following is JAVA implementation of this approach.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">JAVA<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program to find closest pair in an array<br\/>class ClosestPair<br\/>{<br\/>    \/\/ ar1[0..m-1] and ar2[0..n-1] are two given sorted<br\/>    \/\/ arrays\/ and x is given number. This function prints<br\/>    \/\/ the pair from both arrays such that the sum of the<br\/>    \/\/ pair is closest to x.<br\/>    void printClosest(int ar1[], int ar2[], int m, int n, int x)<br\/>    {<br\/>        \/\/ Initialize the diff between pair sum and x.<br\/>        int diff = Integer.MAX_VALUE;<br\/> <br\/>        \/\/ res_l and res_r are result indexes from ar1[] and ar2[]<br\/>        \/\/ respectively<br\/>        int res_l = 0, res_r = 0;<br\/> <br\/>        \/\/ Start from left side of ar1[] and right side of ar2[]<br\/>        int l = 0, r = n-1;<br\/>        while (l&lt;m &amp;&amp; r&gt;=0)<br\/>        {<br\/>           \/\/ If this pair is closer to x than the previously<br\/>           \/\/ found closest, then update res_l, res_r and diff<br\/>           if (Math.abs(ar1[l] + ar2[r] - x) &lt; diff)<br\/>           {<br\/>               res_l = l;<br\/>               res_r = r;<br\/>               diff = Math.abs(ar1[l] + ar2[r] - x);<br\/>           }<br\/> <br\/>           \/\/ If sum of this pair is more than x, move to smaller<br\/>           \/\/ side<br\/>           if (ar1[l] + ar2[r] &gt; x)<br\/>               r--;<br\/>           else  \/\/ move to the greater side<br\/>               l++;<br\/>        }<br\/> <br\/>        \/\/ Print the result<br\/>        System.out.print(&quot;The closest pair is [&quot; + ar1[res_l] +<br\/>                         &quot;, &quot; + ar2[res_r] + &quot;]&quot;);<br\/>    }<br\/> <br\/>    \/\/ Driver program to test above functions<br\/>    public static void main(String args[])<br\/>    {<br\/>        ClosestPair ob = new ClosestPair();<br\/>        int ar1[] = {1, 4, 5, 7};<br\/>        int ar2[] = {10, 20, 30, 40};<br\/>        int m = ar1.length;<br\/>        int n = ar2.length;<br\/>        int x = 38;<br\/>        ob.printClosest(ar1, ar2, m, n, x);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Find the closest pair from two sorted arrays &#8211; Searching and Sorting &#8211; Given two sorted arrays and a number x, find the pair whose sum is closest to x and the pair has an element from each array.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[83519,71670,83512],"tags":[72937,72963,72927,72931,72949,72957,72969,72922,72920,72925,72944,72972,72933,72943,72926,72923,72934,72951,72967,72924,72954,72962,72945,72929,72921,72946,72956,70756,72928,72953,72964,72941,72936,72968,72947,72948,72919,72939,72959,72974,72952,72950,72971,72955,72970,72938,72930,72932,72940,72973,72935,72101,72965,72960,72942,72966,70402,72958,72961],"class_list":["post-25316","post","type-post","status-publish","format-standard","hentry","category-closest-pair","category-searching-and-sorting","category-sorted-array","tag-algorithm-design-kleinberg-pdf","tag-bentley-1980","tag-c-pair","tag-closer","tag-closest-h-and-m","tag-closest-javascript","tag-closest-one","tag-closest-pair","tag-closest-pair-algorithm","tag-closest-pair-algorithm-divide-and-conquer","tag-closest-pair-algorithm-pseudocode","tag-closest-pair-of-points","tag-closest-pair-of-points-algorithm","tag-closest-pair-of-points-divide-and-conquer-algorithm","tag-closest-pair-of-points-problem","tag-closest-pair-problem","tag-closest-pair-problem-algorithm","tag-closest-point","tag-closest-point-algorithm","tag-closests","tag-conquer-and-divide","tag-conquer-points","tag-conquest-2","tag-convex-hull-algorithm","tag-coord-sets","tag-define-closer","tag-divide-and-concur","tag-divide-and-conquer","tag-divide-and-conquer-algorithm","tag-divide-and-conquer-algorithm-examples","tag-divide-and-conquer-examples","tag-divide-and-conquer-meaning","tag-divide-and-conquer-strategy","tag-divide-conquer","tag-divide-in-python","tag-find-the-closest","tag-find-the-closest-pair-from-two-sorted-arrays","tag-find-the-distance-between-each-pair-of-points","tag-find-the-distance-between-the-pair-of-points","tag-find-the-distance-from-the-point-to-the-given-plane","tag-finding-the-closest-pair-of-points","tag-force-pair","tag-infiniti-cars-wiki","tag-mastering-algorithms-with-c-pdf","tag-matlab-find-closest-value","tag-multiplication-algorithm","tag-n-log-n","tag-python-division","tag-python-pair","tag-shortest-distance-between-two-cities","tag-shortest-distance-between-two-points","tag-sorting-algorithms-pdf","tag-sweep-line","tag-sweep-line-algorithm","tag-the-closest-one","tag-the-closest-pair-problem","tag-the-master-algorithm-pdf","tag-the-shortest-distance-between-two-points","tag-what-is-the-shortest-distance-between-two-points"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25316","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=25316"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25316\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25316"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25316"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25316"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}