#include <iostream>
using namespace std;
template <typename T>
T sum(T arr[], T n)//减治求和
{
return (n < 1) ? 0 : sum(arr, n - 1) + arr[n - 1];
//递归求解加号前面的表达式
}
template <typename T>
T asum(T arr[], T low, T high)//分治求和
{
if (low == high)return arr[low];
int mid = (low + high) >> 1; //>>1相当于/2
return asum(arr, low, mid) + asum(arr, mid + 1, high);
}
template <typename T>
void swap(T *a, T *b)
{
T temp;
temp = *a;
*a = *b;
*b = temp;
}
template <typename T>
void reverse(T *arr, T low, T high)//数组倒置
{
if (low < high)
{
swap(arr[low], arr[high]);
reverse(arr, low + 1, high - 1);
}
}
template <typename T>
void areverse(T *arr, T low, T high)//数组倒置迭代版
{
while (low < high) swap(arr[low++], arr[high--]);
}
template <typename T>
void max2(T arr[], int low, int high, T &x1, T &x2)//递归+分治 求最大两个值
{
if (low + 2 == high) {
if (arr[low] > arr[low + 1]) {
x1 = arr[low];
x2 = arr[low + 1];
}
else {
x1 = arr[low + 1];
x2 = arr[low];
}
return;
}
if (low + 3 == high) {
x1 = arr[low];
x2 = arr[low + 1];
if (x1 < x2) {
T t = 0;
t = x1;
x1 = x2;
x2 = t;
}
if ((arr[low + 2] > x2) && (arr[low + 2] < x1))
x2 = arr[low + 2];
if (arr[low + 2] > x1) {
x2 = x1;
x1 = arr[low + 2];
}
return;
}
int mid = (low + high) >> 1;
T x1L, x2L; max2(arr, low, mid, x1L, x2L);
T x1R, x2R; max2(arr, mid, high, x1R, x2R);
if (x1L > x1R) {
x1 = x1L;
x2 = (x1R > x2L) ? x1R : x2L;
}
else {
x1 = x1R;
x2 = (x1L > x2R) ? x1L : x2R;
}
}
int main()
{
int a[7] = { 1,2,3,4,5,6,7 };
cout << sum(a, 7) << endl;//减治求和
cout << asum(a, 0, 6) << endl;//分治求和
int c = 1;
int b = 2;
reverse(a, 0, 6);//倒置
for (int i = 0; i < 7; i++)
cout << a[i] << " ";
cout << endl;
areverse(a, 0, 6);//迭代倒置
for (int i = 0; i < 7; i++)
cout << a[i] << " ";
cout << endl;
int x1, x2;
max2(a, 0, 7, x1, x2);//迭代+分治 求最大两个值
cout << x1 << " " << x2 << endl;
return 0;
}
递归分治减治学习笔记
最新推荐文章于 2020-10-07 10:05:59 发布