{"id":26628,"date":"2017-12-21T21:02:10","date_gmt":"2017-12-21T15:32:10","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26628"},"modified":"2017-12-21T21:02:10","modified_gmt":"2017-12-21T15:32:10","slug":"java-programming-randomized-algorithms","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-programming-randomized-algorithms\/","title":{"rendered":"Java Programming &#8211; Randomized Algorithms (1\/2) Approximate Median"},"content":{"rendered":"<p><strong>Problem Statement : <\/strong>Given an unsorted array A[] of n numbers and \u03b5 &gt; 0, compute an element whose rank (position in sorted A[]) is in the range [(1 \u2013 \u03b5)n\/2, (1 + \u03b5)n\/2].<br \/>\nFor \u00bd Approximate Median Algorithm &amp;epsilom; is 1\/2 =&gt; rank should be in the range [n\/4, 3n\/4]\n<p>We can find k\u2019th smallest element in <a href=\"http:\/\/www.geeksforgeeks.org\/kth-smallestlargest-element-unsorted-array-set-2-expected-linear-time\/\" target=\"_blank\" rel=\"noopener\">O(n) expected time<\/a> and <a href=\"http:\/\/www.geeksforgeeks.org\/kth-smallestlargest-element-unsorted-array-set-3-worst-case-linear-time\/\" target=\"_blank\" rel=\"noopener\">O(n) worst case<\/a> time.<\/p>\n<p><strong>What if we want in less than O(n) time with low probable error allowed?<\/strong><br \/>\nFollowing steps represent an algorithm that is O((Log n) x (Log Log n)) time and produces incorrect result with probability less than or equal to 2\/n<sup>2<\/sup>.<br \/>\nRandomly choose k elements from the array where k=c log n (c is some constant)<br \/>\nInsert then into a set.<br \/>\nSort elements of the set.<br \/>\nReturn median of the set i.e. (k\/2)th element from the set.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Java Program<\/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 Approximate Median using<br\/>   1\/2 Approximate Algorithm *\/<br\/>import java.util.Iterator;<br\/>import java.util.Random;<br\/>import java.util.TreeSet;<br\/> <br\/> <br\/>class Test<br\/>{<br\/>    static int arr[] = new int[]{1, 3, 2, 4, 5, 6, 8, 7} ;<br\/>     <br\/>    \/\/ This function returns the Approximate Median<br\/>    static int randApproxMedian(int n)<br\/>    {<br\/>        \/\/ Declaration for the random number <br\/>        Random r = new Random();<br\/>         <br\/>        if (n==0)<br\/>            return 0;<br\/>         <br\/>        double k1 = 10*Math.log(n); \/\/ Taking c as 10<br\/>      <br\/>        int k = (int)k1;<br\/>         <br\/>        \/\/ A treeset stores unique elements in sorted order<br\/>        TreeSet s = new TreeSet&lt;Integer&gt;();<br\/>        for (int i=0; i&lt;k; i++)<br\/>        {<br\/>            \/\/ Generating a random index<br\/>            \/\/ Random number generated will be in the range [0,n-1]<br\/>            int index = r.nextInt(n);<br\/>      <br\/>            \/\/Inserting into the set<br\/>            s.add(arr[index]);<br\/>        }<br\/>      <br\/>        Iterator&lt;Integer&gt; itr = s.iterator();<br\/>         <br\/>        int temp = s.size()\/2 - 1;<br\/>         <br\/>        for (int i = 0; i &lt; temp; i++) {<br\/>            itr.next();<br\/>        }<br\/>      <br\/>        \/\/ Return the median<br\/>        return itr.next();<br\/>    }<br\/>  <br\/>    \/\/ Driver method to test the above function<br\/>    public static void main(String[] args) {<br\/>     <br\/>        System.out.println(&quot;Approximate Median is &quot; + randApproxMedian(arr.length));<br\/>     <br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Time Complexity:<\/strong><br \/>\nWe use a set provided by the STL in C++. In STL Set, insertion for each element takes O(log k). So for k insertions, time taken is O (k log k).<br \/>\nNow replacing k with c log n<br \/>\n=&gt;O(c log n (log (clog n))) =&gt;O (log n (log log n))<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>How is probability of error less than 2\/n<sup>2<\/sup>?<\/strong><br \/>\nAlgorithm makes an error if the set S has at least k\/2 elements are from the Left Quarter or Right Quarter.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-26629\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/median.png\" alt=\"median\" width=\"867\" height=\"268\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/median.png 867w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/median-300x93.png 300w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/median-768x237.png 768w\" sizes=\"(max-width: 867px) 100vw, 867px\" \/><\/p>\n<p>It is quite easy to visualize this statement since the median which we report will be (k\/2)th element and if we take k\/2 elements from the left quarter(or right quarter) the median will be from the left quarter (or the right quarter).<\/p>\n<p>An array can be divided into 4 quarters each of size n\/4. So P(selecting left quarter) is 1\/4. So what is the probability that at least k\/2 elements are from the Left Quarter or Right Quarter? This probability problem is same as below :<\/p>\n<p>Given a coin which gives HEADS with probability 1\/4 and TAILS with 3\/4. The coin is tossed k times. What is the probability that we get at least k\/2 HEADS is less than or equal to?<\/p>\n<p><b>Explanation:<\/b><\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-26630\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/probability.png\" alt=\"probability\" width=\"692\" height=\"389\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/probability.png 692w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/probability-300x168.png 300w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/probability-470x264.png 470w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/probability-640x360.png 640w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/probability-215x120.png 215w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/probability-414x232.png 414w\" sizes=\"(max-width: 692px) 100vw, 692px\" \/><\/p>\n<pre>If we put k = c log n for c = 10, we get \r\nP &lt;= (1\/2)<sup>2log n<\/sup>\r\nP &lt;= (1\/2)<sup>log n2<\/sup>\r\nP &lt;= n<sup>-2<\/sup>\r\n<\/pre>\n<p>Probability of selecting at least k\/2 elements from the left quarter) &lt;= 1\/n<sup>2<\/sup><br \/>\nProbability of selecting at least k\/2 elements from the left or right quarter) &lt;= 2\/n<sup>2<\/sup><\/p>\n<p>Therefore algorithm produces incorrect result with probability less that or equal to 2\/n<sup>2<\/sup>.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>It is quite easy to visualize this statement since the median which we report will be (k\/2)th element and if we take k\/2 elements from the left quarter.<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,1,2139,77748],"tags":[70150,70246,79462,77863,78792,78781,70326,79473,79472,79464,79466,74263,73371,70026,79465,79463,79468],"class_list":["post-26628","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-coding","category-java","category-randomized-algorithms","tag-cormen-solutions","tag-design-analysis-and-algorithm","tag-how-to-write-an-algorithm","tag-java-algorithm-interview-questions","tag-java-programming-exercises-with-solutions-pdf","tag-logical-programming-questions","tag-permutation-and-combination-pdf","tag-permutation-and-combination-problems-with-solutions-pdf","tag-probability-problems-pdf","tag-programming-logic-questions","tag-quicksort-algorithm-in-data-structure-pdf","tag-software-engineer-interview-questions-and-answers","tag-the-worst-case-occur-in-linear-search-algorithm-when","tag-time-complexity-of-binary-search","tag-what-is-an-algorithm","tag-write-an-algorithm","tag-writing-algorithms"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26628","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\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26628"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26628\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26628"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26628"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26628"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}