输入一个有序数组有10个元素,用二分查找法查找其中一个元素,并输出其下标
时间: 2023-05-20 17:03:09 浏览: 104
可以使用以下代码实现:
```python
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
target = 7
index = binary_search(arr, target)
print(index)
```
输出结果为:3,即目标元素7在数组中的下标为3。
相关问题
C语言在一个递增有序的线性表中利用二分查找法查找数据元素X
在一个递增有序的线性表中利用二分查找法查找数据元素X的C语言代码如下:
```
int binary_search(int array[], int len, int target) {
int left = 0, right = len - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (array[mid] == target) {
return mid;
} else if (array[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
```
这个函数接收三个参数:一个递增有序的数组 `array`、数组的长度 `len` 和要查找的元素 `target`。函数返回值为找到的元素的下标,如果元素不存在则返回 -1。
函数使用了二分查找法的思想,每次将数组分成左半部分和右半部分,然后将目标元素与中间元素进行比较,如果相同则返回中间元素的下标,否则根据目标元素与中间元素的大小关系确定下一步查找的方向。如果目标元素比中间元素大,则在右半部分继续查找;否则在左半部分继续查找。不断重复这个过程,直到找到目标元素或者确定目标元素不存在。
完整代码C语言在一个递增有序的线性表中利用二分查找法查找数据元素X
以下是完整的 C 语言代码实现,在一个递增有序的线性表中利用二分查找法查找数据元素 X:
```c
#include <stdio.h>
int binary_search(int array[], int len, int target) {
int left = 0, right = len - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (array[mid] == target) {
return mid;
} else if (array[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int len = sizeof(array) / sizeof(int);
int target = 5;
int index = binary_search(array, len, target);
if (index != -1) {
printf("Target found at index %d\n", index);
} else {
printf("Target not found\n");
}
return 0;
}
```
这个程序首先定义了一个递增有序的数组 `array`,数组的长度为 `len`,要查找的元素为 `target`。然后调用 `binary_search()` 函数进行查找,将返回值存储在 `index` 变量中。如果返回值不为 -1,则说明目标元素存在于数组中,打印出目标元素的下标。否则,说明目标元素不存在于数组中,打印出提示信息。
在这个程序中,我们调用了 `sizeof()` 函数来获取数组的长度,这是一种常见的获取数组长度的方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)