写个c++程序,用递归法求长度为n的一维数组的最小元素值
时间: 2024-02-21 07:58:59 浏览: 54
以下是使用递归法求长度为n的一维数组的最小元素值的C++程序:
```cpp
#include <iostream>
using namespace std;
int findMin(int arr[], int n) {
if (n == 1)
return arr[0];
return min(arr[n-1], findMin(arr, n-1));
}
int main() {
int arr[] = {5, 3, 8, 1, 9};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "The minimum element in the array is: " << findMin(arr, n);
return 0;
}
```
在这个程序中,`findMin`函数使用递归来计算最小元素值。当数组长度为1时,函数返回数组中唯一的元素值。否则,函数返回数组中最后一个元素和数组前n-1个元素的最小值。在`main`函数中,我们声明了一个整型数组,并使用sizeof运算符计算数组长度。然后,我们调用`findMin`函数来计算最小元素值,并将其打印到控制台上。
相关问题
利用递推减半技术,写出求长度为n的数组中最大元素的C++递归算法
好的,我可以回答这个问题。以下是利用递推减半技术,写出求长度为n的数组中最大元素的C递归算法:
```
#include <stdio.h>
int getMax(int arr[], int start, int end) {
if (start == end) { // 只有一个元素
return arr[start];
} else if (start + 1 == end) { // 有两个元素
return arr[start] > arr[end] ? arr[start] : arr[end];
} else { // 有多个元素
int mid = (start + end) / 2;
int max1 = getMax(arr, start, mid);
int max2 = getMax(arr, mid + 1, end);
return max1 > max2 ? max1 : max2;
}
}
int main() {
int arr[] = {10, 5, 17, 28, 3, 15};
int size = sizeof(arr) / sizeof(int);
int max = getMax(arr, 0, size - 1);
printf("The maximum element is %d\n", max);
return 0;
}
```
这个算法的基本思路是对数组进行递归分治,每次将数组分成两个部分。一直递归到只有一个元素或两个元素时,比较它们的大小并返回较大的数值。最后将所有返回来的数值进行比较,得到最大元素。
写一个递归函数,实现求一个一维数组的所有元素之和
好的,以下是一个递归函数来实现求一个一维数组的所有元素之和的示例代码:
```python
def array_sum(arr):
if len(arr) == 0:
return 0
else:
return arr[0] + array_sum(arr[1:])
```
这个函数接受一个一维数组作为参数,如果数组为空,则返回0,否则返回数组的第一个元素加上递归调用该函数并传入数组的剩余部分的结果。当递归调用到最后一个元素时,递归将停止并返回结果。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)