简体   繁体   English

同时最小和最大

[英]Simultaneous minimum and maximum

I've tried to implement an algorithm that would search for both minimum and maximum elements in a given array, and used the ideas from Cormen's Introduction to Algorithms . 我试图实现一种算法,在给定的数组中搜索最小和最大元素,并使用Cormen的算法导论中的想法。 My code compiles and starts working, outputs the generated random array and then does nothing for a really long time. 我的代码编译并开始工作,输出生成的随机数组,然后在很长一段时间内什么都不做。 Why could that be? 为什么会这样?

The code is this: 代码是这样的:

// fast min and max --cormen exercise 1.cpp: entry point
//implemented from a verbal description in cormen's book, p 243

#include "stdafx.h"
#include <vector>
#include <ctime>
#include <cstdlib>
#include <iostream>

struct min_and_max
{
    int min, max;
};


min_and_max find_min_and_max(std::vector<int>& A)
{
    int n = A.size();
    int min, max;
    if (n%2 == 1)
        min = max = A[0];
    if (n%2 == 0)
        if (A[0] < A[1])
        {
            min = A[0];
            max = A[1];
        }
        else
        {
            min = A[1];
            max = A[0];
        }
    for(int i = 2; i < A.size(); (i + 2))
    {
        if (A[i] < A[i+1])
        {
            if (min > A[i])
                min = A[i];
            if (max < A[i+1])
                max = A[i+1];
        }
        else
        {
            if (min > A[i+1])
                min = A[i+1];
            if (max < A[i])
                max = A[i];
        }
    }
    min_and_max result;
    result.min = min;
    result.max = max;

    return result;
}

int main()
{
    std::srand(std::time(0));
    std::vector<int> A(10);
    for (auto i = 0; i < A.size(); i++)
        {
            A[i] = rand() % 1000;
            std::cout << A[i] << " ";           
        }
    std::cout << std::endl; //IT GOES AS FAR AS THIS
    std::cout << "The array has been analyzed; its' minimum is " << find_min_and_max(A).min << "and its' maximum is " << find_min_and_max(A).max << std::endl;

    return 0;
}
 for(int i = 2; i < A.size(); (i + 2))

i + 2不会改变i的值,你需要使用i += 2

The problem lies here: 问题在于:

for(int i = 2; i < A.size(); (i + 2))

You never actually increment i , thus causing an infinite loop. 你永远不会实际增加i ,从而导致无限循环。

change it to: 将其更改为:

for(int i = 2; i < A.size(); i+=2)

Additional to the given answers, if you're using c++11 you can simplify your algorithm using lambdas and the std::for_each function: 除了给定的答案之外,如果您使用的是c ++ 11,则可以使用lambdasstd::for_each函数简化算法:

#include <algorithm>
#include <iostream>
#include <cmath>

int main() { 
    int array[] = { -8, 8, 0, 9, 5, -3, 4, 6, -1, 15, 31 };
    int min, max;
    // User std::for_each(v.begin(), v.end(), ...) for either vector or list
    std::for_each(std::begin(array), std::end(array), [&min, &max](int elem) { 
        max = std::max(max, elem);
        min = std::min(min, elem);
    });
    std::cout << min << ", " << max << std::endl;
    return 0;
}

And maybe it could be even simpler 也许它可能更简单

Update: As @Blastfurnace pointed out, the std::minmax_element function could be used to further reduce the code needed for searching both the min and max element, yielding this shorter version: 更新:正如@Blastfurnace指出的那样, std::minmax_element函数可用于进一步减少搜索min和max元素所需的代码,从而产生这个更短的版本:

#include <algorithm>
#include <iostream>
#include <vector>   

int main() { 
    std::vector<int> values = { -8, 8, 0, 9, 5, -3, 4, 6, -1, 15, 31 };
    auto minAndMax = std::minmax_element(values.begin(), values.end());
    std::cout << *minAndMax.first << ", " << *minAndMax.second << std::endl;
    return 0;
}

Is important to note that everything done in this answer, besides being OT, is for the sake of learning, to give the OP alternatives to improve his (or her) work and help other users that could have the same requirement. 重要的是要注意,除了OT之外,在这个答案中所做的一切都是为了学习,提供OP替代方案来改进他(或她)的工作并帮助其他可能具有相同要求的用户。

In any case the algorithm is incorrect because the vector can have the size equal to 0. In this case 1) you try to access alements that are not exist and 2) you return undefined values from the function. 在任何情况下算法都是不正确的,因为向量的大小可以等于0.在这种情况下1)您尝试访问不存在的alement和2)您从函数返回未定义的值。 The more correct approach is to return indexes of the minimum and maximum elements and in the case if the vector is empty return a pair of A.size(). 更正确的方法是返回最小和最大元素的索引,如果向量为空,则返回一对A.size()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM