Search in an almost sorted array
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:
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
Input: arr[] = {10, 3, 40, 20, 50, 80, 70}, key = 90
Output: -1
-1 is returned to indicate element is not present
my sollution is
#include<stdio.h>
int main(void)
{
int arr[]={10, 3, 40, 20, 50, 80, 70};
int i = binSearch(arr,0,8,9,50);
if(i==1)
printf("found!!!\n");
else
printf("not found!!!\n");
return 0;
}
int binSearch(int *arr,int low,int high,int length,int searchEle)
{
int mid=(low+high)/2;
if(low>high)
{
return 0;
}
else
{
if(arr[mid]==searchEle)
{
return 1;
}
else if(arr[mid-1]==searchEle)
{
return 1;
}
else if(arr[mid+1]==searchEle)
{
return 1;
}
else if(arr[mid]<searchEle)
{
return binSearch(arr,mid+1,high,length,searchEle);
}
else
{
return binSearch(arr,low,mid-1,length,searchEle);
}
}
}
let me know if I am wrong at some point !!! :)