c++有15个数按由小到大的顺序存放在一个数组中,输入一个数,要求用折半查找法找出该数是数组中第几个元素的值。如果该数不在数组中,则打印出“无此数”
时间: 2023-05-03 22:00:15 浏览: 172
题意:给定一个大小为15的数数组,输入一个数,要求用折半查找法找出该数是数组中第几个元素的值。如果该数不在数组中,则打印出“无此数”。
解法:首先需要将数组排序,使用快速排序等方法。然后利用折半查找法,即每次查找中间位置,判断该位置的值与目标值的大小关系,然后不断缩小查找范围直到找到目标值或者确定目标值不在数组中。最后输出目标值在数组中的位置或者“无此数”。
相关问题
用c++写有15个数按小由到大顺序存放在一个数组中,输入一个数,要求用折半查找法找出该数在数组中的下标。
好的,下面是使用C++实现的代码:
```c++
#include <iostream>
using namespace std;
int binarySearch(int arr[], int l, int r, int x)
{
while (l <= r) {
int m = l + (r - l) / 2;
// Check if x is present at mid
if (arr[m] == x)
return m;
// If x greater, ignore left half
if (arr[m] < x)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
// if we reach here, then element was not present
return -1;
}
int main()
{
int arr[15] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int x;
cout << "Enter a number to search: ";
cin >> x;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
```
代码中,我们首先定义了一个长度为15的数组,然后输入一个要查找的数x,调用`binarySearch`函数进行折半查找,最后输出结果。`binarySearch`函数使用while循环实现了折半查找算法,如果找到了就返回下标,找不到就返回-1。
用c++语言写一个程序有15个书按由大到小存放在一个数组中,输入一个数,要求用折半查找法找出该数是数组的第几个元素的值。若不在这个数组中则打印“无此数”
好的,以下是用C++语言编写的程序,实现了按照从大到小的顺序存放15个数,并使用折半查找法查找给定的数在数组中的位置:
```
#include <iostream>
using namespace std;
int main() {
int arr[15] = { 99, 88, 77, 66, 55, 44, 33, 22, 21, 20, 19, 18, 17, 16, 15 };
int target;
int left = 0;
int right = 14;
int mid;
bool found = false;
cout << "请输入一个数:";
cin >> target;
while (left <= right) {
mid = (left + right) / 2;
if (arr[mid] == target) {
found = true;
cout << "该数是数组的第" << mid + 1 << "个元素的值" << endl;
break;
}
else if (arr[mid] < target) {
right = mid - 1;
}
else {
left = mid + 1;
}
}
if (!found) {
cout << "无此数" << endl;
}
return 0;
}
```
程序中首先定义了一个包含15个数的数组`arr`,然后根据从大到小的顺序进行了初始化。接着,程序要求用户输入一个数`target`,并利用折半查找法在数组中查找该数。如果找到了,程序输出该数在数组中的位置;如果没找到,程序输出“无此数”。