Find a Fixed Point in an array with duplicates allowed 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 duplicate elements are allowed in the array.

Here we will use binary search approach to solve this problem in O(log n) time. But we need some modification, if the normal binary search is used, then it may fail for duplicate elements. To check left, we have to start through min(mid – 1, midValue), and to check right, we have to start through max(mid + 1, midValue).

Example

 Live Demo

#include<iostream>
using namespace std;
int getFixedPoint(int arr[], int left, int right) {
   if (right < left)
      return -1;
   int mid = (left + right) / 2;
   int midValue = arr[mid];  
   if (mid == arr[mid])
      return mid;
   int leftindex = min(mid - 1, midValue);
   int l = getFixedPoint(arr, left, leftindex);
   if (l >= 0)
      return l;
   int rightindex = max(mid + 1, midValue);
   int r = getFixedPoint(arr, rightindex, right);
   return r;
}
int main() {
   int arr[] = {-10, -5, 2, 2, 2, 3, 4, 7, 10, 12, 17};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout<<"Fixed Point: "<< getFixedPoint(arr, 0, n-1);
}

Output

Fixed Point: 2
raja
Published on 24-Oct-2019 16:07:06
Advertisements