
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find a Fixed Point in an array with duplicates allowed 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 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
#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
- Related Articles
- Find Equal (or Middle) Point in a sorted array with duplicates in C++
- Check if array contains contiguous integers with duplicates allowed in Python
- Find All Duplicates in an Array in C++
- Find a Fixed Point (Value equal to index) in a given array in C++
- Print distinct sorted permutations with duplicates allowed in input in C++
- Find a Fixed Point (Value equal to index) in a given array in C++ Program
- Insert Delete GetRandom O(1) - Duplicates allowed in C++
- Count number of triplets with product equal to given number with duplicates allowed in C++
- Fixed Point in Python
- Finding all duplicate numbers in an array with multiple duplicates in JavaScript
- Maximum sum of pairwise product in an array with negative allowed in C++
- Check for duplicates in an array in MongoDB?
- Find Duplicates of array using bit array in Python
- Find Duplicates of array using bit array in C++
- Maximum sum of pairwise product in an array with negative allowed in C++ program

Advertisements