If there is any Fixed Point present in array, else returns -1.
Note that integers in array can be negative.
Example :
Input: arr[] = {-2, -1, 1, 3, 5}
Output: 3 // arr[3] == 3
Input: arr[] = {-4, -1, 1, 2, 5, 8}
Output: -1 // No Fixed Point
First Simple Method : Linear Search
for(i = 0; i < n; i++){
if(arr[i] == i) return i;
}
Complexity O(n)
Method 2 : Divide and Conquer (As numbers is sorted we can use it as binary search)
Thanks to Dhaval for suggesting this Code.
int indexSearch(int arr[], int low, int high)
{
if(high >= low)
{
int mid = (low + high)/2;
if(mid == arr[mid])
return mid;
if(mid > arr[mid])
return indexSearch(arr, (mid + 1), high);
else
return indexSearch(arr, low, (mid -1));
}
/* Return -1 if there is no Fixed Point */
return -1;
}
int main()
{
int arr[] = {-2, -1, 1, 3, 5};
int n = sizeof(arr)/sizeof(arr[0]);
printf(“Fixed Point is %d”, indexSearch(arr, 0, n-1));
getchar();
return 0;
}