diff --git a/Algorithms.hpp b/Algorithms.hpp index 078f423..6bbcce7 100644 --- a/Algorithms.hpp +++ b/Algorithms.hpp @@ -46,6 +46,12 @@ bool quickSort(std::vector 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 int64_t search(std::vector nums, T num); +//This function finds the minimum element in a vector +template +T findMin(std::vector arr); +//This function finds the maximum element in a vector +template +T findMax(std::vector arr); template @@ -230,6 +236,50 @@ int64_t search(std::vector nums, T num){ return -1; } +//This function finds the minimum of a vector +template +T findMin(std::vector 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 +T findMax(std::vector 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; +} + }