Find Element in Sorted Array
EasyPractice library · +10 XPbinary searcharrays
Given a sorted array of N distinct integers, find the index of a given integer X. If X is not present in the array, output -1.
The array is sorted in ascending order. The indices are 0-based.
Input
The first line contains two integers N and X, separated by a space. The second line contains N space-separated integers, representing the sorted array.
Output
Print a single integer: the 0-based index of X if found, otherwise -1.
Constraints
1 <= N <= 1000 -10^9 <= array elements, X <= 10^9 The array elements are distinct and sorted in ascending order.
Time limit 1 s (native code; slower languages get more)Memory 256 MB15 hidden tests
Example 1
Input
5 7 1 3 5 7 9
Output
3
X is present at index 3.
Example 2
Input
4 6 2 4 8 10
Output
-1
X is not present in the array.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 7 1 3 5 7 9
Example 2 input
4 6 2 4 8 10