Mobile coding works. A laptop is faster for long sessions.

Problem

Two numbers n and x are read, followed by n integers representing an array v sorted in ascending order (v[0] < v[1] < ... < v[n-1]). Print the position (1-based) at which x appears in the array, or -1 if x is not present. The search must be performed using a recursive binary search function.

Define a recursive function binSearch(v, lo, hi, x) that returns the position of x in v between indices lo and hi, or -1 if not found. At each call compute mid = (lo + hi) / 2 and:

  • if v[mid] == x, return mid + 1 (1-based position);
  • if x < v[mid], recurse on the left half [lo, mid-1];
  • if x > v[mid], recurse on the right half [mid+1, hi].

Base case: if lo > hi, return -1.

Input format

Input input.txt

The first line contains `n` and `x`, separated by a space. The second line contains the `n` elements of the array, separated by spaces, in strictly ascending order. - `1 <= n <= 50` - Array elements are integers with absolute value at most `1.000.000.000`, strictly ascending. - The solution must use recursion.

Output format

Output output.txt

The program prints the position of `x` (from 1 to `n`) or `-1` if not present, followed by a newline.

Example

input
6 7

1 3 5 7 9 11
output
4

Ready to solve this challenge?

Create a free account to write code, submit solutions, and track your progress.

⌨️ Keyboard Shortcuts

Code Editor
Run Code
Ctrl Enter
Submit Code
Ctrl Shift Enter
Format Code
Shift Alt F
Toggle Comment
Ctrl /
Undo
Ctrl Z
Redo
Ctrl Y
Navigation
Global Search
/
Show Shortcuts
?
Close Modal
Esc

🔍 Interactive Debugger

0 / 0

Analyzing your code...

📦 Variables

No variables yet

📚 Call Stack
main() line 1
📤 Output