I have two pieces of code for finding the three largest numbers in a given array. The first one uses std::sort to sort an array of three elements each time it finds a number larger than the current smallest of the three. The second one performs manual sorting using if statements to maintain the order after a larger number is found.
Is there a significant difference in terms of efficiency between these two methods? Given the fact that the std::sort function is designed for sorting collections of arbitrary size, and the size of the array in this case is always small (3 elements), would the manual sorting be more efficient than using std::sort?
I understand that the overall time complexity of both functions is O(n), where n is the size of the input array, but I'm wondering about the efficiency of the sorting operation itself.
Here are the two versions of the code:
#include <vector>
std::vector<int> findThreeLargestNumbers(const std::vector<int>& array) {
constexpr int COUNT {3};
std::vector<int> maxArray{ array.begin(),array.begin()+COUNT};
std::sort(maxArray.begin(), maxArray.end());
for (int i = COUNT; i < array.size(); ++i)
{
if (array[i] > maxArray[0])
{
maxArray[0] = array[i];
std::sort(maxArray.begin(), maxArray.end());
}
}
return maxArray;
}
#include <vector>
std::vector<int> findThreeLargestNumbers(const std::vector<int>& array) {
constexpr int COUNT{ 3 };
std::vector<int> maxArray{ array.begin(),array.begin() + COUNT };
std::sort(maxArray.begin(), maxArray.end());
for (int i = COUNT; i < array.size(); ++i)
{
if (array[i] > maxArray[0])
{
maxArray[0] = array[i];
if (maxArray[0] > maxArray[1])
{
swap(maxArray[0], maxArray[1]);
}
if (maxArray[1] > maxArray[2])
{
swap(maxArray[1], maxArray[2]);
}
}
}
return maxArray;
}