Assume that you are writing sorting algorithms, and that you want the ability to select between ascending and descending order. The only change required to do this for comparison sorts is to use the inverse of the comparison operator (for example: > becomes <). This begs the question, why is it not possible to change operators on the fly?
A simple bubble sort for ascending order:
private T[] BubbleAscending(T[] sortMe)
{
bool stopMe = true;
int stopRecurse = sortMe.Length - 1;
int optimizeMe = stopRecurse;
for (int i = 0; i < stopRecurse && stopMe; i++)
{
stopMe = false;
for (int j = 0; j < optimizeMe; j++)
{
if (sortMe[j].CompareTo(sortMe[j + 1]) > 0)
{
Swap(sortMe, j, j + 1);
stopMe = true;
}
}
optimizeMe--;
}
return sortMe;
}
Now we have to have a Bubble sort for descending order:
private T[] BubbleDescending(T[] sortMe)
{
bool stopMe = true;
int stopRecurse = sortMe.Length - 1;
int optimizeMe = stopRecurse;
for (int i = 0; i < stopRecurse && stopMe; i++)
{
stopMe = false;
for (int j = 0; j < optimizeMe; j++)
{
if (sortMe[j].CompareTo(sortMe[j + 1]) < 0)
{
Swap(sortMe, j, j + 1);
stopMe = true;
}
}
optimizeMe--;
}
return sortMe;
}
Now we have to have some logic to allow the user to easily select between them:
public T[] BubbleSort(T[] sortMe, bool descending)
{
if (!descending)
return BubbleAscending(CopyArray(sortMe));
else
return BubbleDescending(CopyArray(sortMe));
}
Wouldn't it be much simpler if we could do this?
public T[] BubbleSort(T[] sortMe, bool descending)
{
if (!descending)
operator comparison = >;
else if (descending)
operator comparison = <;
bool stopMe = true;
int stopRecurse = sortMe.Length - 1;
int optimizeMe = stopRecurse;
for (int i = 0; i < stopRecurse && stopMe; i++)
{
stopMe = false;
for (int j = 0; j < optimizeMe; j++)
{
if (sortMe[j].CompareTo(sortMe[j + 1]) comparison 0)
{
Swap(sortMe, j, j + 1);
stopMe = true;
}
}
optimizeMe--;
}
return sortMe;
}
std::sort
(C++<algorithm>
library) accepts a user defined comparison function object. Evenqsort
(<stdlib.h>
) accepts a comparison function. $\endgroup$