I have a sort function that accepts a Boolean parameter desc
(descending) which sorts in reverse order if true
& algo
is an enum class that selects the algorithm (here the subset of the code is for algo::BUBBLE
(bubblesort))
Using this inline conditional statement (if (!desc ? A[j] > A[j + 1] : A[j] < A[j + 1])
), I can eliminate rewriting the entire code for reverse sort as it evaluates the appropriate condition based on the desc
flag. But I wonder if this can create unnecessary overhead as it checks the flag repeatedly [(n-1)*(1+2+...+n-1) times]. Will this overhead come out as substantial for larger data elements? More code or more overhead?
void Array<T>::sort(bool desc = false, algo a)
{
if (algo == algo::BUBBLE)
{
bool wasSwapped = true;
for (size_t i = 0; i < size - 1 && wasSwapped; i++)
{
switched = false;
for (size_t j = 0; j < size - i - 1; j++)
{
if (!desc ? A[j] > A[j + 1] : A[j] < A[j + 1])
{
wasSwapped = true;
swap(A[j], A[j + 1]);
}
}
}
}
}
A
and size
are private data members (Array pointer and size respectively).
For code clarity, it will be better to make that a non-member function template and pass it a compare functor. Make sure to put the function in your application's namespace so there is no confusion with the functions of the same name from the std
namespace.
Assuming Array<T>::A
is accessible,
namespace MyApp
{
template <typename T, typename Compare = std::less<T>>
void sort(Array<T>& array, algo a, Compare compare = Compare());
{
if (a == algo::BUBBLE)
{
bool wasSwapped = true;
for (size_t i = 0; i < size - 1 && wasSwapped; i++)
{
switched = false;
for (size_t j = 0; j < size - i - 1; j++)
{
if (!compare(array.A[j], array.A[j + 1]))
{
wasSwapped = true;
swap(array.A[j], array.A[j + 1]);
}
}
}
}
}
}
Now you can use:
Array<int> a = { ... };
MyApp::sort(a, algo::BUBBLE); // std::less<int> is the default functor.
MyApp::sort(a, algo::BUBBLE, std::greater<int>()); // Explicit compare functor.