帮我编写一个程序:有10个数,按由大到小的顺序存放在一个数组中,输入一个数,要求用折半查找法找出该数是数组中的第几个数。如果该数不在数组中,则打印出"无此数"
时间: 2024-05-09 16:18:10 浏览: 23
好的,这是一个计算机编程的问题。下面是代码示例:
```python
def binary_search(arr, x):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
return mid + 1
elif arr[mid] < x:
high = mid - 1
else:
low = mid + 1
return "无此数"
arr = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
arr.sort(reverse=True) # 从大到小排序
x = int(input("请输入一个数:"))
result = binary_search(arr, x)
print(result)
```
输入一个数后,程序会输出该数在数组中的位置。如果该数不在数组中,则会输出"无此数"。
相关问题
用C语言写程序:+有15个数按由大到小顺序存放在一个数组中,输入一个数,要求用
根据提供的引用内容,以下是用C语言编写的折半查找法程序:
```c
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int x) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] < x)
right = mid - 1;
else
left = mid + 1;
}
return -1;
}
int main() {
int arr[] = {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int n = sizeof(arr) / sizeof(arr[0]);
int x;
printf("请输入要查找的数:");
scanf("%d", &x);
int result = binarySearch(arr, 0, n - 1, x);
if (result == -1)
printf("无此数\n");
else
printf("该数是数组中第%d个元素的值\n", result + 1);
return 0;
}
```
C语言编写程序,输入6个整数存入数组中,按输入顺序的逆序存放在该数组中并输出
以下是C语言程序实现:
```c
#include <stdio.h>
int main() {
int arr[6];
int i;
// 输入6个整数存入数组中
printf("请输入6个整数:\n");
for (i = 0; i < 6; i++) {
scanf("%d", &arr[i]);
}
// 按输入顺序的逆序存放在该数组中
for (i = 0; i < 3; i++) {
int temp = arr[i];
arr[i] = arr[5 - i];
arr[5 - i] = temp;
}
// 输出反转后的数组
printf("反转后的数组为:");
for (i = 0; i < 6; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
这个程序中,我们首先定义了一个长度为6的整型数组`arr`,并通过for循环读取6个整数并存储到该数组中。接下来,我们使用for循环反转数组元素的顺序。最后,我们输出反转后的数组元素。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)