Find a Fixed Point (Value equal to index) in a given array in C++

C++Server Side ProgrammingProgramming

Here we will see how to find fixed point in a given array. In array one element will be denoted as fixed point if the value is same as its index. This program will return the value if any, otherwise return -1. The array can hold negative numbers also. And the data elements are sorted.

Here we will use binary search approach to solve this problem in O(log n) time. At first we will check whether the middle element is fixed point or not, if yes, then return it, if not, then there will be two situations, if the index of middle element is greater than the value at index, if index is greater, then there is a chance to get the fixed point at the right hand side, otherwise at the left hand side.

Example

 Live Demo

#include<iostream>
using namespace std;
int getFixedPoint(int arr[], int left, int right) {
   if(right >= left){
      int mid = (left + right)/2; /*low + (high - low)/2;*/
      if(mid == arr[mid])
         return mid;
      if(mid > arr[mid])
         return getFixedPoint(arr, (mid + 1), right);
      else
         return getFixedPoint(arr, left, (mid -1));
   }
   return -1;
}
int main() {
   int arr[] = {-10, -1, 0, 3, 10, 11, 9, 50, 56};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout<<"Fixed Point: "<< getFixedPoint(arr, 0, n-1);
}

Output

Fixed Point: 3
raja
Published on 24-Oct-2019 12:34:24
Advertisements