Find a Fixed Point in a given array

Fixed point in a array means A[i] = i
Example :
Input: arr[] = {1, 8, 2, 9, 17}
Output: 2 // arr[2] == 2

Algorithm :
Using linear search

Code :

int findFixedpoint(int arr[], int n)
{
    int i;
    for(i = 0; i < n; i++)
    {
        if(arr[i] == i)
            return i;
    }
 
    return -1; //If no fixed point 
}

Note : you can use binary search if array is sorted , it will search in O(log n) time .

Leave a Reply

Your email address will not be published. Required fields are marked *

For Inserting code :
Paste your code in the comment form, select it and then click the language link

C | C++ | Java |

*