

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find a Fixed Point (Value equal to index) in a given array in C++
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
#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
- Related Questions & Answers
- Find a Fixed Point (Value equal to index) in a given array in C++ Program
- Find a Fixed Point in an array with duplicates allowed in C++
- Mask array elements equal to a given value in Numpy
- Program to find maximum value at a given index in a bounded array in Python
- Mask array elements not equal to a given value in Numpy
- Find Equal (or Middle) Point in a sorted array with duplicates in C++
- Set MongoDB compound index with a fixed value field
- Fixed Point in Python
- Check which element in a masked array is equal to a given value in NumPy
- Mask array elements greater than or equal to a given value in Numpy
- Find the closest index to given value in JavaScript
- Check which element in a masked array is not equal to a given value in NumPy
- Mask an array where less than or equal to a given value in Numpy
- Find a partition point in array in C++
- Find an equal point in a string of brackets using C++.
Advertisements