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