![]() |
VOOZH | about |
Given a sorted integer array arr[] consisting of distinct elements, where some elements of the array are moved to either of the adjacent positions, i.e. arr[i] may be present at arr[i-1] or arr[i+1].
Given an integer target. You have to return the index ( 0-based ) of the target in the array. If target is not present return -1.
Examples :
Input: arr[] = [10, 3, 40, 20, 50, 80, 70], target = 40
Output: 2
Explanation: Output is index of 40 in given array i.e. 2Input: arr[] = [10, 3, 40, 20, 50, 80, 70], target = 90
Output: -1
Explanation: 90 is not present in the array.
Table of Content
A idea is to linearly search the given key in array arr[]. To do so, run a loop starting from index 0 to n - 1, and for each index i, check if arr[i] == target, if so print the index i, else move to the next index. At last, if no such index is found, print -1.
Below is given the implementation:
2
The idea is to compare the key with middle 3 elements, if present then return the index. If not present, then compare the key with middle element to decide whether to go in left half or right half.
Comparing with middle element is enough as all the elements after mid+2 must be greater than element mid and all elements before mid-2 must be smaller than mid element.
Follow the steps below to implement the idea:
Below is given the implementation:
2