gpt4 book ai didi

c++ - 递归查找数组中的最小值和最大值

转载 作者:行者123 更新时间:2023-11-28 00:31:53 28 4
gpt4 key购买 nike

我做了一个递归函数来从一个可能包含任意数量元素的数组中找到最大值和最小值。这样做的主要原因是想从 Dicom 图像的像素数据中找到最小最大值。我将这个递归函数作为测试代码,其中我用 0-1000 范围内的随机数填充了 int 类型的数组。我的代码如下。我给出了完整的代码,您可以自己在 Visual Studio 中非常轻松地运行该程序。

#include <stdio.h>
#include <string>
#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;

void recursMax(int* a, int size, int* maxValue)
{
int half = size/2;
int* newMax = new int[half];
for(int i=0; i<half; i++)
{
newMax[i]=a[i]>a[size-i-1]?a[i]:a[size-i-1];
}
if(half>1)
{
recursMax(newMax, half, maxValue);
}
if(half == 1)
{
*maxValue = newMax[0];
delete [] newMax;
}
}

void recursMin(int* a, int size, int* minValue)
{
int half = size/2;
int* newMin = new int[half];
for(int i=0; i<half; i++)
{
newMin[i]=a[i]<a[size-i-1]?a[i]:a[size-i-1];
}

if(half>1)
{
recursMin(newMin, half, minValue);
}
if(half == 1)
{
*minValue = newMin[0];
delete [] newMin;
}
}

int main ()
{
int size = 100;
int* a = new int[size];
srand(time(NULL));
for(int i=0; i<size; i++)
{
a[i]=rand()%1000;
cout<<"Index : "<<i+1<<", "<<a[i]<<endl;
}
cout<<endl<<endl<<"Now we look to find the max!"<<endl;
int maxValue = 0;
int minValue = 0;
recursMax(a, size, &maxValue);
cout<<maxValue<<endl;
recursMin(a, size, &minValue);
cout<<"Now we look for the min value!"<<endl<<minValue<<endl;
cout<<"Checking the accuracy! First for Max value!"<<endl;
for(int i=0; i<size; i++)
{
cout<<"Index : "<<i+1<<", "<<maxValue-a[i]<<endl;
}
cout<<"Checking the accuracy! Now for min value!"<<endl;
for(int i=0; i<size; i++)
{
cout<<"Index : "<<i+1<<", "<<a[i]-minValue<<endl;
}
delete [] a;
return 0;
}

我的问题是,您认为我的算法工作正常吗?我有些怀疑。另外,我是否正确处理或维护内存?或者代码中会不会有一些内存泄露?

最佳答案

您应该从最后一个if 语句中删除delete [] newMax;,否则您将永远无法释放内存。像这样:

if(half == 1)
{
*maxValue = newMax[0];
}
delete [] newMax;

recursMin 函数也是如此。

您的算法似乎有效,但过度了。使用递归和分配内存只是为了找到最小值和最大值不是一个好的风格。

关于c++ - 递归查找数组中的最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22532152/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com