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:
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.
Console.Write("Fixed Point is "+ linearSearch(arr, n));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to check fixed point
// in an array using linear search
functionlinearSearch($arr, $n)
{
for($i= 0; $i< $n; $i++)
{
if($arr[$i] == $i)
return$i;
}
// If no fixed point present then
// return -1
return-1;
}
// Driver Code
$arr= array(-10, -1, 0, 3, 10,
11, 30, 50, 100);
$n= count($arr);
echo"Fixed Point is ".
linearSearch($arr, $n);
// This code is contributed by Sam007
?>
Javascript
<script>
// JavaScript program to check fixed point
// in an array using linear search
functionlinearSearch(arr, n)
{
let i;
for(i = 0; i < n; i++)
{
if(arr[i] == i)
returni;
}
/* If no fixed point present
then return -1 */
return-1;
}
// Driver Code
let arr = [-10, -1, 0, 3, 10, 11, 30, 50, 100];
let n = arr.length;
document.write("Fixed Point is "
+ linearSearch(arr, n));
</script>
Output:
Fixed Point is 3
Time Complexity: O(n) Auxiliary Space: O(1)
Method 2 (Binary Search) First check whether middle element is Fixed Point or not. If it is, then return it; otherwise if the index of middle + 1 element is less than or equal to the value at the high index, then Fixed Point(s) might lie on the right side of the middle point (obviously only if there is a Fixed Point). Similarly, check if the index of middle – 1 element is greater than or equal to the value at the low index, then Fixed Point(s) might lie on the left side of the middle point.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
This article is being improved by another user right now. You can suggest the changes for now and it will be under the article’s discussion tab.
You will be notified via email once the article is available for improvement.
Thank you for your valuable feedback!
Please Login to comment...