The results
2 6 18 20 16 11 9 12 13 3max_value: 20min_value: 2comp_times: 17
14 5 1 2 17 4 15 7 7 16max_value: 17min_value: 1comp_times: 19
1 1 3 9 17 7 13 9 20 15max_value: 20min_value: 1comp_times: 16
1 1 8 16 3 10 18 18 10 6max_value: 18min_value: 1comp_times: 17
14 18 7 16 17 6 20 12 14 18max_value: 20min_value: 6comp_times: 18
4 17 12 12 12 5 4 17 15 7max_value: 17min_value: 4comp_times: 19
19 4 14 4 10 18 15 20 4 15max_value: 20min_value: 4comp_times: 19
14 6 8 4 8 17 12 9 12 16max_value: 17min_value: 4comp_times: 19
9 17 20 8 20 16 5 12 12 9max_value: 20min_value: 5comp_times: 18
17 1 1 4 4 11 8 13 20 4max_value: 20min_value: 1comp_times: 19
average_comp_times: 18.1
The corresponding codes:
//get the least comparing times to get the minimum and maximum values
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
const int N = 10;
void randa(int a[]);
void disp_array(int a[]);
int get_min_max(int a[], int &min, int &max);
int main()
{
srand((unsigned)time(NULL));
int a[N];
double sum_comp_times = 0.0;
for (int i = 0; i < 10; i++) {
randa(a);
disp_array(a);
//obtain the minimum and maximum values in the random array
int max_value = 0;
int min_value = 0;
int comp_times = 0;
comp_times = get_min_max(a, min_value, max_value);
std::cout << "max_value: " << max_value << std::setw(3);
std::cout << "min_value: " << min_value << std::setw(3);
std::cout << "comp_times: " << comp_times << std::endl;
sum_comp_times += comp_times;
}
double average_comp_times = sum_comp_times / 10.0;
std::cout << "average_comp_times: " << average_comp_times << std::endl;
}
void randa(int a[])
{
for (int i = 0; i < N; i++)
{
a[i] = rand() % 20 + 1;
}
}
void disp_array(int a[])
{
for (int i = 0; i < N; i++)
{
std::cout << std::setw(3) << a[i];
}
}
int get_min_max(int a[], int &min, int &max)
{
int comp_times =0; //tag the comparing time to get the max and min values
int temp_min = a[0]; //tag the temporary min value in array at present
int temp_max = a[0]; //tag the temporary max value in array at present
for (int i = 0; i < N; i++) {
++comp_times;
if(a[i] > temp_max)
temp_max = a[i];
else{
++comp_times;
if (a[i] < temp_min)
temp_min = a[i];
}
}
min = temp_min;
max = temp_max;
return comp_times;
}