mirror of
https://bitbucket.org/Mattrixwv/my-classes.git
synced 2025-12-06 18:23:57 -05:00
Added functions for finding the minimum and maximum elements in a vector
This commit is contained in:
@@ -46,6 +46,12 @@ bool quickSort(std::vector<T> nums);
|
||||
//This is a function that performs a search on a vector and returns the subscript of the item being searched for (-1 if not found)
|
||||
template<class T>
|
||||
int64_t search(std::vector<T> nums, T num);
|
||||
//This function finds the minimum element in a vector
|
||||
template<class T>
|
||||
T findMin(std::vector<T> arr);
|
||||
//This function finds the maximum element in a vector
|
||||
template<class T>
|
||||
T findMax(std::vector<T> arr);
|
||||
|
||||
|
||||
template<class T>
|
||||
@@ -230,6 +236,50 @@ int64_t search(std::vector<T> nums, T num){
|
||||
return -1;
|
||||
}
|
||||
|
||||
//This function finds the minimum of a vector
|
||||
template<class T>
|
||||
T findMin(std::vector<T> arr){
|
||||
T min; //For the smallest element
|
||||
|
||||
//Make sure the vector is not empty
|
||||
if(arr.size() > 0){
|
||||
//Use the first element as the smallest element
|
||||
min = arr.at(0);
|
||||
//Run through every element in the vector, checking it against the current minimum
|
||||
for(int cnt = 1;cnt < arr.size();++cnt){
|
||||
//If the current element is smaller than the minimum, make it the new minimum
|
||||
if(arr.at(cnt) < min){
|
||||
min = arr.at(cnt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Return the element
|
||||
return min;
|
||||
}
|
||||
|
||||
//This function finds the maximum of a vector
|
||||
template<class T>
|
||||
T findMax(std::vector<T> arr){
|
||||
T max; //For the largest element
|
||||
|
||||
//Make sure the vector is not empty
|
||||
if(arr.size() > 0){
|
||||
//Use the first element as the largest element
|
||||
max = arr.at(0);
|
||||
//Run through every element in the vector, checking it against the current minimum
|
||||
for(int cnt = 1;cnt < arr.size();++cnt){
|
||||
//If the current element is larger than the maximum, make it the new maximum
|
||||
if(arr.at(cnt) > max){
|
||||
max = arr.at(cnt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Return the element
|
||||
return max;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user