-->
当前位置:首页 > 题库

PROGRAMMING:The process of binary search

Luz5年前 (2021-05-10)题库385
This problem requires the use of binary search method, in the given $$n $$integer in ascending order to find $$x $, and output the intermediate results of each step in the search process. If the elements in the array $$a $$have the same value as $$x $$, output the corresponding subscript (subscript starts from 0); If not found, output "not found". If the input $$n $$integers are not arranged in descending order, or the same number appears, output "invalid value".
The algorithm steps of binary search method are described as follows:
Let the array of $$n $$elements $$a $$be arranged in ascending order, and use the 'left' and 'right' variables to represent the search interval, that is, to find $$x $$in the 'a [left] ~ a [right]' interval. The initial state is' left = 0, right = n-1 '. First, compare the $$x $$to be found with the middle position element 'a [mid]' ('mid = (left + right) / 2 ') of the search interval. If it is equal, it will be found; If 'x < a [mid]', because the array is arranged in ascending order, you can continue to search in the interval 'a [left] ~ a [mid-1]'; If 'x > a [mid]', continue to search in the interval 'a [mid + 1] ~ a [right]'. That is, new interval values' left 'and' right 'are generated according to the comparison with intermediate elements. When' left > right 'appears, it means that there is no element with the value of $$x $.
###Input format:
Input in line 1, give a positive integer $$n $$($$1 / Le n / Le 10 $$) and an integer $$x $$, and in line 2, enter $$n $$integers separated by spaces. The topic guarantees that the data does not exceed the range of long integers.
###Output format:
The intermediate results of the corresponding steps in the search process are output in each line, and the output is in the format of "[left, right] [mid]". Tip: there is no space between adjacent numbers and symbols.
If found, output the corresponding subscript (subscript starts from 0); If not, output "not found" in one line.
If the input $$n $$integers are not arranged in descending order, or the same number appears, output "invalid value".
###Input sample 1:
```in
10 2
1 2 3 4 5 6 7 8 9 10
```
###Output sample 1:
```out
[0,9][4]
[0,3][1]
one
```
###Input example 2:
```in
4 5
71 74 78 100
```
###Output example 2:
```out
[0,3][1]
[0,0][0]
Not Found
```
###Input sample 3:
```in
5 5
39 60 80 80 100
```
###Output example 3:
```out
Invalid Value
```






answer:If there is no answer, please comment