{"id":25246,"date":"2017-10-15T16:21:50","date_gmt":"2017-10-15T10:51:50","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25246"},"modified":"2017-10-15T16:21:50","modified_gmt":"2017-10-15T10:51:50","slug":"find-k-closest-elements-given-value","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/find-k-closest-elements-given-value\/","title":{"rendered":"Find k closest elements to a given value"},"content":{"rendered":"<p>Given a sorted array arr[] and a value X, find the k closest elements to X in arr[]. <span id=\"more-129639\"><\/span><br \/>\nExamples:<\/p>\n<pre>Input: K = 4, X = 35\r\n       arr[] = {12, 16, 22, 30, 35, 39, 42, \r\n               45, 48, 50, 53, 55, 56}\r\nOutput: 30 39 42 45\r\n<\/pre>\n<p>Note that if the element is present in array, then it should not be in output, only the other closest elements are required.<\/p>\n<p>In the following solutions, it is assumed that all elements of array are distinct.<\/p>\n<p>A <strong>simple solution <\/strong>is to do linear search for k closest elements.<br \/>\n1) Start from the first element and search for the crossover point (The point before which elements are smaller than or equal to X and after which elements are greater). This step takes O(n) time.<br \/>\n2) Once we find the crossover point, we can compare elements on both sides of crossover point to print k closest elements. This step takes O(k) time.<\/p>\n<p>The time complexity of the above solution is O(n).<\/p>\n<p>An <strong>Optimized Solution<\/strong> is to find k elements in O(Logn + k) time. The idea is to use <a href=\"http:\/\/geeksquiz.com\/binary-search\/\" target=\"_blank\" rel=\"noopener noreferrer\">Binary Search<\/a> to find the crossover point. Once we find index of crossover point, we can print k closest elements in O(k) time.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>C++<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">c++<\/span> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">#include&lt;stdio.h&gt;<br\/> <br\/>\/* Function to find the cross over point (the point before<br\/>   which elements are smaller than or equal to x and after<br\/>   which greater than x)*\/<br\/>int findCrossOver(int arr[], int low, int high, int x)<br\/>{<br\/>  \/\/ Base cases<br\/>  if (arr[high] &lt;= x) \/\/ x is greater than all<br\/>    return high;<br\/>  if (arr[low] &gt; x)  \/\/ x is smaller than all<br\/>    return low;<br\/> <br\/>  \/\/ Find the middle point<br\/>  int mid = (low + high)\/2;  \/* low + (high - low)\/2 *\/<br\/> <br\/>  \/* If x is same as middle element, then return mid *\/<br\/>  if (arr[mid] &lt;= x &amp;&amp; arr[mid+1] &gt; x)<br\/>    return mid;<br\/> <br\/>  \/* If x is greater than arr[mid], then either arr[mid + 1]<br\/>    is ceiling of x or ceiling lies in arr[mid+1...high] *\/<br\/>  if(arr[mid] &lt; x)<br\/>      return findCrossOver(arr, mid+1, high, x);<br\/> <br\/>  return findCrossOver(arr, low, mid - 1, x);<br\/>}<br\/> <br\/>\/\/ This function prints k closest elements to x in arr[].<br\/>\/\/ n is the number of elements in arr[]<br\/>void printKclosest(int arr[], int x, int k, int n)<br\/>{<br\/>    \/\/ Find the crossover point<br\/>    int l = findCrossOver(arr, 0, n-1, x);<br\/>    int r = l+1;   \/\/ Right index to search<br\/>    int count = 0; \/\/ To keep track of count of elements already printed<br\/> <br\/>    \/\/ If x is present in arr[], then reduce left index<br\/>    \/\/ Assumption: all elements in arr[] are distinct<br\/>    if (arr[l] == x) l--;<br\/> <br\/>    \/\/ Compare elements on left and right of crossover<br\/>    \/\/ point to find the k closest elements<br\/>    while (l &gt;= 0 &amp;&amp; r &lt; n &amp;&amp; count &lt; k)<br\/>    {<br\/>        if (x - arr[l] &lt; arr[r] - x)<br\/>            printf(&quot;%d &quot;, arr[l--]);<br\/>        else<br\/>            printf(&quot;%d &quot;, arr[r++]);<br\/>        count++;<br\/>    }<br\/> <br\/>    \/\/ If there are no more elements on right side, then<br\/>    \/\/ print left elements<br\/>    while (count &lt; k &amp;&amp; l &gt;= 0)<br\/>        printf(&quot;%d &quot;, arr[l--]), count++;<br\/> <br\/>    \/\/ If there are no more elements on left side, then<br\/>    \/\/ print right elements<br\/>    while (count &lt; k &amp;&amp; r &lt; n)<br\/>        printf(&quot;%d &quot;, arr[r++]), count++;<br\/>}<br\/> <br\/>\/* Driver program to check above functions *\/<br\/>int main()<br\/>{<br\/>   int arr[] ={12, 16, 22, 30, 35, 39, 42,<br\/>               45, 48, 50, 53, 55, 56};<br\/>   int n = sizeof(arr)\/sizeof(arr[0]);<br\/>   int x = 35, k = 4;<br\/>   printKclosest(arr, x, 4, n);<br\/>   return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>JAVA<\/strong><\/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 k closest elements to a given value<br\/>class KClosest<br\/>{<br\/>    \/* Function to find the cross over point (the point before<br\/>       which elements are smaller than or equal to x and after<br\/>       which greater than x)*\/<br\/>    int findCrossOver(int arr[], int low, int high, int x)<br\/>    {<br\/>        \/\/ Base cases<br\/>        if (arr[high] &lt;= x) \/\/ x is greater than all<br\/>            return high;<br\/>        if (arr[low] &gt; x)  \/\/ x is smaller than all<br\/>            return low;<br\/> <br\/>        \/\/ Find the middle point<br\/>        int mid = (low + high)\/2;  \/* low + (high - low)\/2 *\/<br\/> <br\/>        \/* If x is same as middle element, then return mid *\/<br\/>        if (arr[mid] &lt;= x &amp;&amp; arr[mid+1] &gt; x)<br\/>            return mid;<br\/> <br\/>        \/* If x is greater than arr[mid], then either arr[mid + 1]<br\/>          is ceiling of x or ceiling lies in arr[mid+1...high] *\/<br\/>        if(arr[mid] &lt; x)<br\/>            return findCrossOver(arr, mid+1, high, x);<br\/> <br\/>        return findCrossOver(arr, low, mid - 1, x);<br\/>    }<br\/> <br\/>    \/\/ This function prints k closest elements to x in arr[].<br\/>    \/\/ n is the number of elements in arr[]<br\/>    void printKclosest(int arr[], int x, int k, int n)<br\/>    {<br\/>        \/\/ Find the crossover point<br\/>        int l = findCrossOver(arr, 0, n-1, x); <br\/>        int r = l+1;   \/\/ Right index to search<br\/>        int count = 0; \/\/ To keep track of count of elements<br\/>                       \/\/ already printed<br\/> <br\/>        \/\/ If x is present in arr[], then reduce left index<br\/>        \/\/ Assumption: all elements in arr[] are distinct<br\/>        if (arr[l] == x) l--;<br\/> <br\/>        \/\/ Compare elements on left and right of crossover<br\/>        \/\/ point to find the k closest elements<br\/>        while (l &gt;= 0 &amp;&amp; r &lt; n &amp;&amp; count &lt; k)<br\/>        {<br\/>            if (x - arr[l] &lt; arr[r] - x)<br\/>                System.out.print(arr[l--]+&quot; &quot;);<br\/>            else<br\/>                System.out.print(arr[r++]+&quot; &quot;);<br\/>            count++;<br\/>        }<br\/> <br\/>        \/\/ If there are no more elements on right side, then<br\/>        \/\/ print left elements<br\/>        while (count &lt; k &amp;&amp; l &gt;= 0)<br\/>        {<br\/>            System.out.print(arr[l--]+&quot; &quot;);<br\/>            count++;<br\/>        }<br\/> <br\/> <br\/>        \/\/ If there are no more elements on left side, then<br\/>        \/\/ print right elements<br\/>        while (count &lt; k &amp;&amp; r &lt; n)<br\/>        {<br\/>            System.out.print(arr[r++]+&quot; &quot;);<br\/>            count++;<br\/>        }<br\/>    }<br\/> <br\/>    \/* Driver program to check above functions *\/<br\/>    public static void main(String args[])<br\/>    {<br\/>        KClosest ob = new KClosest();<br\/>        int arr[] = {12, 16, 22, 30, 35, 39, 42,<br\/>                     45, 48, 50, 53, 55, 56<br\/>                    };<br\/>        int n = arr.length;<br\/>        int x = 35, k = 4;<br\/>        ob.printKclosest(arr, x, 4, n);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>39 30 42 45<\/pre>\n<p>The time complexity of this method is O(Logn + k).<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Find k closest elements to a given value &#8211; searching and sorting &#8211; start from the first element and search for the crossover point (The point before which elements are smaller than or equal to X and after which elements are greater). <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,71670],"tags":[72525,72561,72515,72521,72541,72558,72518,72536,72545,72553,72551,72537,72522,72529,72548,72528,72538,72546,72520,72516,72517,72524,72569,72542,72567,72547,72530,72519,72565,72555,72559,72533,72531,72556,72560,72523,72550,72539,72552,72570,72568,72571,72540,72544,72532,72566,72526,72557,72554,72534,72562,72564,72543,72563,72527,72535,72549,72572],"class_list":["post-25246","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-searching-and-sorting","tag-ball-tree","tag-data-mining-knn","tag-find-k-closest-elements-to-a-given-value","tag-find-neighbors","tag-k-nearest","tag-k-nearest-neighbor","tag-k-nearest-neighbor-algorithm","tag-k-nearest-neighbor-algorithm-example","tag-k-nearest-neighbor-classification","tag-k-nearest-neighbor-classification-algorithm","tag-k-nearest-neighbor-classification-in-data-mining","tag-k-nearest-neighbor-classifier","tag-k-nearest-neighbor-example","tag-k-nearest-neighbor-python","tag-k-nearest-neighbor-python-code","tag-k-nearest-neighbors-algorithm","tag-k-nearest-neighbour-algorithm-in-data-mining","tag-k-nearest-neighbour-example-in-data-mining","tag-k-nearest-neighbours","tag-knn","tag-knn-algorithm","tag-knn-algorithm-example","tag-knn-algorithm-implementation","tag-knn-algorithm-in-data-mining","tag-knn-algorithm-pseudocode","tag-knn-algorithm-python","tag-knn-classification","tag-knn-classifier","tag-knn-classifier-algorithm","tag-knn-classifier-example","tag-knn-classifier-python","tag-knn-data-mining","tag-knn-example","tag-knn-in-data-mining","tag-knn-method","tag-knn-python","tag-knn-python-code","tag-knn-r","tag-knnsearch","tag-nearest","tag-nearest-neighbor","tag-nearest-neighbor-algorithm","tag-nearest-neighbor-algorithm-example","tag-nearest-neighbor-classification","tag-nearest-neighbor-classifier","tag-nearest-neighbor-example","tag-nearest-neighbor-search","tag-nearest-neighbour-algorithm-in-data-mining","tag-nearest-neighbour-classification","tag-nearest-neighbour-classifier","tag-nearest-neighbour-in-data-mining","tag-neighbor-finder","tag-neighborhood-search","tag-neighbors-1","tag-python-knn","tag-python-nearest-neighbor","tag-r-knn","tag-tree-ball"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25246","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=25246"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25246\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25246"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25246"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25246"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}