ronith

6/14/2018 - 6:09 AM

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. Basically the element arr[i] can only be swapped with either arr[i+1] or arr[i-1].

For example consider the array {2, 3, 10, 4, 40}, 4 is moved to next position and 10 is moved to previous position.

Example :

Input: arr[] = {10, 3, 40, 20, 50, 80, 70}, key = 40 Output: 2 Output is index of 40 in given array

Idea: 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.

```
// https://www.geeksforgeeks.org/search-almost-sorted-array/
#include<iostream>
using namespace std;
int func (int a[], int l, int r, int x){
if (l <= r){
int m=(l+r)/2;
if (a[m] == x)
return m;
if (a[m-1] == x)
return m-1;
if (a[m+1] == x)
return m+1;
if (a[m] < x)
return func(a,m+2,r,x);
if (a[m] > x)
return func(a,l,m-2,x);
}
return -1;
}
int main(){
int n,x;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
cout<< "Enter the search element:";
cin>>x;
int j=func(a,0,n-1,x);
if (j != -1)
cout<< "Element is present at index: "<<j;
else
cout<< "Element is not present.";
}
```