Saturday, February 14, 2015

Search an element in a sorted and pivoted array

An element in a sorted array can be found in O(log n) time via binary search. But suppose I rotate the sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time.
sortedPivotedArray


// search in two arrays symeltaneously , given that you have pivot element index.
// in the below code pivotPoint is the index of pivot element. // find it your own way.
// searchEle is the element to be searched.
// a is pointer to array.
// arrSize is size of array

int binSearchInRotatedArray(int *a,int arrSize,int pivotPoint,int searchEle)
{

int low1=0,low2=0,high1=0,high2=0,mid1=0,mid2=0;

high1=pivotPoint;
low2=pivotPoint+1;
high2=arrSize-1;

while(1)
{


if(low1>high1)
{
// do nothing..
}
else
{
mid1=(low1+high1)/2;


if(a[mid1]==searchEle)
{
return mid1;
}




else if(a[mid1]>searchEle)
{
high1=mid1-1;

}
else
{
low1=mid1+1;
}

}


if(low2>high2)
{
// do nothing..
}
else
{
mid2=(low2+high2)/2;


if(a[mid2]==searchEle)
{
return mid2;
}



else if(a[mid2]>searchEle)
{
high2=mid2-1;
}
else
{
low2=mid2+1;
}

}

if((low1>high1) && (low2>high2))  // because I have continue the process untill both sides of the array is completly scanned.
{
return -1;

}

}// end of while



}






int main(int argc,char *argv[])
{

int a[]={15,16,19,20,25,1,3,4,5,7,10,14};

int sum=0,i=0,j=0;

int arrSize=sizeof(a)/sizeof(a[0]);


for(j=0;j<arrSize;j++)
{
i=binSearchInRotatedArray(a,arrSize,4,a[j]);

printf("\nyour element %d is at index %d\n",a[j],i);

}
return 0;

}


// time complexity is O(logn) given that you know the index of pivot element.
// so if you find the pivot element it will take O(n) time.
// so total worst case complexity will be n + logn = O(n). // bad idea....


//lets improve this algorithm .
// Here I designed a code which will work even if we do not know the pivot point.
// the worst case time complexity id O(log n).

#include<stdio.h>

int binSearchInRotatedArray(int *a,int arrSize,int searchEle)
{

int low=0,high=(arrSize-1),mid=0;



        while(1)
{
mid=(low+high)/2;



if(a[mid]==searchEle)
{
return mid;
}

else if(a[mid]<searchEle)
{
if(a[high]==searchEle)
{
return high;
}
else  if(a[high]<searchEle)
{
high=mid-1;
}
else
{
low=mid+1;
}

}
else
{
if(a[low]==searchEle)
{
return low;

}
else  if(a[low]<searchEle)
{
high=mid-1;
}
else
{
low=mid+1;
}

}

if(low>=high)
{
return -1;
}

}// end of while


}



int main(int argc,char *argv[])
{

int a[]={15,16,19,20,25,1,3,4,5,7,10,14};

int sum=0,i=0,j=0;

int arrSize=sizeof(a)/sizeof(a[0]);


for(j=0;j<arrSize;j++)
{
i=binSearchInRotatedArray(a,arrSize,a[j]);

printf("\nyour element %d is at index %d\n",a[j],i);

}
return 0;

}

// all the Comments are invited.
// It will be very helpful if you can find the error , please comment below.

No comments:

Post a Comment