It's the code covering the above problem:
#include <iostream>
using namespace std;
#include <vector>
int main()
{
unsigned int n;
cin >> n;
int elementsOfVector;
vector <double> wektor;
for(int i = 0; i<n; i++) {
cin >> elementsOfVector;
wektor.push_back(elementsOfVector);
}
double min = wektor[0];
double max = wektor[1];
if (min > max) {
min = wektor[1];
max = wektor[0];
}
for(int i = 2; i<n; i++) {
if (max < wektor[i]) {
max = wektor[i];
}
else if (min > wektor[i]) {
min = wektor[i];
}
}
cout << "Min " << min << " max " << max;
return 0;
}
According to my analysis: Firstly, we have a for loop to assign all vector's elements with values, we make n-iterations so the time complexity of the action is O(n). Then we have a if statement with condition within it where we compare one value to other but there are always just those two values no matter what n input is so we can assume it's O(1) constant complexity in Big-O notation - not sure if this is correct so I would be grateful If anyone could relate. In the second for loop we make n-2 iterations and the operations inside the for loop are simple arithmetic operations and cost 1 so we can avoid it in big O notation: To sum up n + n = 2n O(2n) so total time complexity is O(n). Am I right?
First part for loop. O(n)
Second part if(min>max) O(1)
Third part for loop O(n)
Total O(n)+O(1)+O(n) = O(n)
The third part since you iterator n-2 times, it's O(n).