S reaction?
2. Bholu, what are you doing lying down in that puddle? Isn't your cricket match on?"
h) Who said these words?
Answers
Answer:
Given an array of n distinct integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in array, else returns -1. Fixed Point in an array is an index i such that arr[i] is equal to i. Note that integers in array can be negative.
Examples:
Input: arr[] = {-10, -5, 0, 3, 7}
Output: 3 // arr[3] == 3
Input: arr[] = {0, 2, 5, 8, 17}
Output: 0 // arr[0] == 0
Input: arr[] = {-10, -5, 3, 4, 7, 9}
Output: -1 // No Fixed Point
Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
Method 1 (Linear Search)
Linearly search for an index i such that arr[i] == i. Return the first such index found. Thanks to pm for suggesting this solution.
// C++ program to check fixed point
// in an array using linear search
#include <bits/stdc++.h>
using namespace std;
int linearSearch(int arr[], int n)
{
int i;
for(i = 0; i < n; i++)
{
if(arr[i] == i)
return i;
}
/* If no fixed point present then return -1 */
return -1;
}
/* Driver code */
int main()
{
int arr[] = {-10, -1, 0, 3, 10, 11, 30, 50, 100};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Fixed Point is " << linearSearch(arr, n);
return 0;
}
// This is code is contributed by rathbhupendra
Output:
Fixed Point is 3
Time Complexity: O(n)
Method 2 (Binary Search)
First check whether middle element is Fixed Point or not. If it is, then return it; otherwise check whether index of middle element is greater than value at the index. If index is greater, then Fixed Point(s) lies on the right side of the middle point (obviously only if there is a Fixed Point). Else the Fixed Point(s) lies on left side.