#K37497. Binary Search in a Sorted Array

    ID: 25989 Type: Default 1000ms 256MiB

Binary Search in a Sorted Array

Binary Search in a Sorted Array

Given an integer n and a target value t, along with a sorted array of n integers, your task is to implement the binary search algorithm to determine any index where t appears in the array. If the target is not present, return -1.

The binary search algorithm works as follows: starting with left = 0 and right = n - 1, repeatedly compute the middle index using $$ mid = \lfloor (left + right) / 2 \rfloor, $$ and compare the element at that index with t. If the element equals t, return the index. Otherwise, if the element is less than t, search the subarray to the right; if it is greater than t, search the subarray to the left. The loop continues while $left \le right$.

Implement the algorithm so that it reads from standard input and writes to standard output.

inputFormat

The input is given as follows:

  • The first line contains two integers n and t, representing the number of elements in the array and the target value, respectively.
  • The second line contains n space-separated integers, which represent the sorted array.

outputFormat

Output a single integer, which is any index where t occurs in the sorted array. If t is not present, output -1.

## sample
5 3
1 2 3 4 5
2