Let,
#include <vector>
vector<int> v {1, 2, 3, -1, -2, -3};
If the vector is sorted in ascending or descending order then you can find it with complexity O(1).
For a vector of ascending order the first element is the smallest element, you can get it by v[0] (0 based indexing) and last element is the largest element, you can get it by v[sizeOfVector-1].
If the vector is sorted in descending order then the last element is the smallest element,you can get it by v[sizeOfVector-1] and first element is the largest element, you can get it by v[0].
If the vector is not sorted then you have to iterate over the vector to get the smallest/largest element.In this case time complexity is O(n), here n is the size of vector.
int smallest_element = v[0]; //let, first element is the smallest one
int largest_element = v[0]; //also let, first element is the biggest one
for(int i = 1; i < v.size(); i++) //start iterating from the second element
{
if(v[i] < smallest_element)
{
smallest_element = v[i];
}
if(v[i] > largest_element)
{
largest_element = v[i];
}
}
You can use iterator,
for (vector<int>:: iterator it = v.begin(); it != v.end(); it++)
{
if(*it < smallest_element) //used *it (with asterisk), because it's an iterator
{
smallest_element = *it;
}
if(*it > largest_element)
{
largest_element = *it;
}
}
You can calculate it in input section (when you have to find smallest or largest element from a given vector)
int smallest_element, largest_element, value;
vector <int> v;
int n;//n is the number of elements to enter
cin >> n;
for(int i = 0;i<n;i++)
{
cin>>value;
if(i==0)
{
smallest_element= value; //smallest_element=v[0];
largest_element= value; //also, largest_element = v[0]
}
if(value<smallest_element and i>0)
{
smallest_element = value;
}
if(value>largest_element and i>0)
{
largest_element = value;
}
v.push_back(value);
}
Also you can get smallest/largest element by built in functions
#include<algorithm>
int smallest_element = *min_element(v.begin(),v.end());
int largest_element = *max_element(v.begin(),v.end());
You can get smallest/largest element of any range by using this functions. such as,
vector<int> v {1,2,3,-1,-2,-3};
cout << *min_element(v.begin(), v.begin() + 3); //this will print 1,smallest element of first three elements
cout << *max_element(v.begin(), v.begin() + 3); //largest element of first three elements
cout << *min_element(v.begin() + 2, v.begin() + 5); // -2, smallest element between third and fifth element (inclusive)
cout << *max_element(v.begin() + 2, v.begin()+5); //largest element between third and first element (inclusive)
I have used asterisk (*), before min_element()/max_element() functions. Because both of them return iterator. All codes are in c++.