已有一个10个元素的整形数组a,且按值从小到大有序。输入一个整数x,然后在数组中查找x,如果找到,输出相应的下标,否则,输出"not found"。。 要求编写函数int bsearch(int *p, int n, int x),找到返回下标,找不到返回-1。
时间: 2023-06-05 21:47:05 浏览: 140
请用英文回复:Given an integer array 'a' of 10 elements, ordered by value from small to large. Input an integer 'x' and search for it in the array. If it is found, output the corresponding index, otherwise output "not found". Write a function 'int bsearch(int *p, int n, int x)' that returns the index if found and returns -1 if not found.
相关问题
、 二分法查找。设已有一个10个元素的整形数组a,且按值从小到大有序排列。输入一个整数x,然后在数组中查找x,如果找到,输出相应的下标,否则,输出“Not Found”。
下面是使用二分法查找的 Python3 代码实现:
```python
def binary_search(a, x):
left, right = 0, len(a) - 1
while left <= right:
mid = (left + right) // 2
if a[mid] == x:
return mid
elif a[mid] < x:
left = mid + 1
else:
right = mid - 1
return -1
a = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
x = 7
index = binary_search(a, x)
if index != -1:
print(f"Found {x} at index {index}")
else:
print("Not Found")
```
输出结果为:
```
Found 7 at index 3
```
如果要查找的元素不在数组中,输出结果为:
```
Not Found
```
已有一个10个元素的整形数组a,且按值从小到大有序。输入一个整数x,然后在数组中查找x,如果找到,输出相应的下标,否则,输出\"not found\"。。 要求编写函数int bsearch(int *p
int bsearch(int *p, int x, int n){
int left = , right = n-1;
while(left <= right){
int mid = (left + right) / 2;
if(p[mid] == x){
return mid;
}
else if(p[mid] < x){
left = mid + 1;
}
else{
right = mid - 1;
}
}
return -1;
}
//调用方式
int a[10] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int x = 7;
int index = bsearch(a, x, 10);
if(index == -1){
printf("not found");
}
else{
printf("index = %d", index);
}
阅读全文