Problem Statement:
Implement the following function, FindSortedArrayRotation,
which takes as its input an array of unique integers that has been sorted
in ascending order, then rotated by an unknown amount X where 0 <=
X <= (arrayLength - 1). An array rotation by amount X moves every
element array
to array[(i + X) % arrayLength]. FindSortedArrayRotation discovers and returns X by examining the array.
Consider performance, memory utilization and code clarity and elegance
of the solution when implementing the function.
C++ Prototype
int FindSortedArrayRotation( int
array[], unsigned length )
{
}
My code so far:
/********************
This program will find the starting value of the array which has been rotated
by X number.
*****/
#include <iostream>
int findSortedRotation(int arr[], int min, int max){
int len = max - min + 1;
int midVal = ((len - 1)/2) + min;
if(len%2 == 0) // If the number is even
{
if(arr[midVal] > arr[midVal + 1])
return arr[midVal + 1];
}
if(len == 2)
{
if(arr[min] > arr[max])
return arr[max];
}
if(len == 1)
{
return arr[max];
}
if(arr[min] > arr[midVal])
return(findSortedRotation(arr, min, midVal));
else if(arr[midVal + 1] > arr[max])
return(findSortedRotation(arr, midVal + 1, max));
else // if the array is already unrotated.
return arr[min];
}
int main(){
int intArray [] = {2, 3, 6, 7, 8, 9, 12};
// int intArray [] = {6, 8, 10, 14, 17, 2, 5};
int num = findSortedRotation(intArray, 0, 6);
std :: cout <<"Array rotated at: " << num << "\n";
getchar();
}
I have tried to use divide and conquer to enhance the performance. The other option could have been something like linear search.
Question 1: Can this algo be further improved?
Question 2: Is it okay to say that the time complexity of the algo is O(logn) as opposed to O(n) for linear search.
Thanks,
mailsubhra.