我试图实现一种算法,该算法将搜索给定数组中的最小和最大元素,并使用了Cormen算法简介中的思想。我的代码编译并开始工作,输出生成的随机数组,然后在很长时间内什么都不做。
为什么会这样呢?
代码是这样的:
// 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
。