{"id":25266,"date":"2017-10-15T16:29:37","date_gmt":"2017-10-15T10:59:37","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25266"},"modified":"2017-10-15T16:29:37","modified_gmt":"2017-10-15T10:59:37","slug":"search-almost-sorted-array","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/search-almost-sorted-array\/","title":{"rendered":"Search in an almost sorted array"},"content":{"rendered":"<p>Given an array which is sorted, but after sorting some elements are moved to either of the adjacent positions, i.e., arr[i] may be present at arr[i+1] or arr[i-1]. Write an efficient function to search an element in this array<span id=\"more-130447\"><\/span>. Basically the element arr[i] can only be swapped with either arr[i+1] or arr[i-1].<\/p>\n<p>For example consider the array {2, 3, 10, 4, 40}, 4 is moved to next position and 10 is moved to previous position.<\/p>\n<p>Example:<\/p>\n<pre>Input: arr[] =  {10, 3, 40, 20, 50, 80, 70}, key = 40\r\nOutput: 2 \r\nOutput is index of 40 in given array\r\n\r\nInput: arr[] =  {10, 3, 40, 20, 50, 80, 70}, key = 90\r\nOutput: -1\r\n-1 is returned to indicate element is not present<\/pre>\n<p>A simple solution is to linearly search the given key in given array. Time complexity of this solution is O(n). We cab modify <a href=\"http:\/\/geeksquiz.com\/binary-search\/\" target=\"_blank\" rel=\"noopener noreferrer\">binary search<\/a> to do it in O(Logn) time.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>The idea is to compare the key with middle 3 elements, if present then return the index. If not present, then compare the key with middle element to decide whether to go in left half or right half. Comparing with middle element is enough as all the elements after mid+2 must be greater than element mid and all elements before mid-2 must be smaller than mid element.<\/p>\n<p>Following is C++ implementation of this approach.<\/p>\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\">\/\/ C++ program to find an element in an almost sorted<br\/>\/\/ array<br\/>#include &lt;stdio.h&gt;<br\/> <br\/>\/\/ A recursive binary search based function. It returns<br\/>\/\/ index of x in given array arr[l..r] is present, <br\/>\/\/ otherwise -1<br\/>int binarySearch(int arr[], int l, int r, int x)<br\/>{<br\/>   if (r &gt;= l)<br\/>   {<br\/>        int mid = l + (r - l)\/2;<br\/> <br\/>        \/\/ If the element is present at one of the middle <br\/>        \/\/ 3 positions<br\/>        if (arr[mid] == x)  return mid;<br\/>        if (mid &gt; l &amp;&amp; arr[mid-1] == x) return (mid - 1);<br\/>        if (mid &lt; r &amp;&amp; arr[mid+1] == x) return (mid + 1);<br\/> <br\/>        \/\/ If element is smaller than mid, then it can only <br\/>        \/\/ be present in left subarray<br\/>        if (arr[mid] &gt; x) return binarySearch(arr, l, mid-2, x);<br\/> <br\/>        \/\/ Else the element can only be present in right subarray<br\/>        return binarySearch(arr, mid+2, r, x);<br\/>   }<br\/> <br\/>   \/\/ We reach here when element is not present in array<br\/>   return -1;<br\/>}<br\/> <br\/>\/\/ Driver program to test above function<br\/>int main(void)<br\/>{<br\/>   int arr[] = {3, 2, 10, 4, 40};<br\/>   int n = sizeof(arr)\/ sizeof(arr[0]);<br\/>   int x = 4;<br\/>   int result = binarySearch(arr, 0, n-1, x);<br\/>   (result == -1)? printf(&quot;Element is not present in array&quot;)<br\/>                 : printf(&quot;Element is present at index %d&quot;, result);<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 an element in an almost sorted array<br\/>class SearchAlmost<br\/>{<br\/>    \/\/ A recursive binary search based function. It returns<br\/>    \/\/ index of x in given array arr[l..r] is present,<br\/>    \/\/ otherwise -1<br\/>    int binarySearch(int arr[], int l, int r, int x)<br\/>    {<br\/>        if (r &gt;= l)<br\/>        {<br\/>            int mid = l + (r - l)\/2;<br\/> <br\/>            \/\/ If the element is present at one of the middle<br\/>            \/\/ 3 positions<br\/>            if (arr[mid] == x)  return mid;<br\/>            if (mid &gt; l &amp;&amp; arr[mid-1] == x) return (mid - 1);<br\/>            if (mid &lt; r &amp;&amp; arr[mid+1] == x) return (mid + 1);<br\/> <br\/>            \/\/ If element is smaller than mid, then it can<br\/>            \/\/ only be present in left subarray<br\/>            if (arr[mid] &gt; x) return binarySearch(arr, l, mid-2, x);<br\/> <br\/>            \/\/ Else the element can only be present in right<br\/>            \/\/ subarray<br\/>            return binarySearch(arr, mid+2, r, x);<br\/>        }<br\/> <br\/>        \/\/ We reach here when element is not present in array<br\/>        return -1;<br\/>    }<br\/> <br\/>    \/\/ Driver method<br\/>    public static void main(String args[])<br\/>    {<br\/>        abc ob = new abc();<br\/>        int arr[] = {3, 2, 10, 4, 40};<br\/>        int n = arr.length;<br\/>        int x = 4;<br\/>        int result = ob.binarySearch(arr, 0, n-1, x);<br\/>        if(result == -1)<br\/>            System.out.println(&quot;Element is not present in array&quot;);<br\/>        else<br\/>            System.out.println(&quot;Element is present at index &quot; +<br\/>                               result);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>Element is present at index 3<\/pre>\n<p>Time complexity of the above function is O(Logn).<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Search in an almost sorted array &#8211; Searching and Sorting &#8211; A simple solution is linearly search given key in given array.Time complexity of solution is O(n).We cab modify binary search to do it in O(Logn) time.<\/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,83512],"tags":[71128,71222,72388,71133,71893,72390,72302,70892,71121,71135,71134,71141,71131,71130,72305,72392,72389,71144,70895,70017,72386,71160,71158,70969,70075,70914,70046,71714,71265,70272,72695,70016,70548,72387,72385,72299,71695,70020,71161,72391,71149,72384,70967,72303,71156,71219,71142,72190,72185],"class_list":["post-25266","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-searching-and-sorting","category-sorted-array","tag-algorithm-for-bubble-sort","tag-algorithm-for-insertion-sort","tag-algorithm-for-sorting","tag-algorithm-of-bubble-sort","tag-algorithm-sort","tag-array-sorting-algorithm","tag-best-sorting","tag-best-sorting-algorithm","tag-bubble-sort-algorithm","tag-bubble-sort-algorithm-in-data-structure","tag-bubble-sort-algorithm-with-example","tag-bubble-sort-animation","tag-bubble-sort-code","tag-bubble-sort-in-data-structure","tag-c-sort","tag-c-sorting-algorithms","tag-common-sorting-algorithms","tag-different-sorting-algorithms","tag-fastest-sorting-algorithm","tag-insertion-sort-algorithm","tag-insertion-sort-animation","tag-insertion-sort-in-data-structure","tag-java-sort","tag-java-sorting-algorithms","tag-linear-sort","tag-most-efficient-sorting-algorithm","tag-quicksort","tag-quicksort-algorithm-in-data-structure","tag-quicksort-example","tag-search-algorithms","tag-search-in-an-almost-sorted-array","tag-selection-sort-algorithm","tag-selection-sort-in-data-structure","tag-simple-sorting-algorithm","tag-sort-algorithm-c","tag-sort-c","tag-sorted","tag-sorting-algorithms","tag-sorting-algorithms-comparison","tag-sorting-algorithms-examples","tag-sorting-algorithms-in-data-structures","tag-sorting-algorithms-in-data-structures-with-examples","tag-sorting-algorithms-java","tag-sorting-algorithms-visualized","tag-sorting-algorithms-with-examples","tag-sorting-in-c","tag-sorting-in-data-structure","tag-sorting-methods","tag-sortings"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25266","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=25266"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25266\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25266"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25266"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25266"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}