Sorting algorithms assume you have a defined comparator. For example, if sorting integers A and B, the A > B
operation allows you to determine if A should be after or before B.
Imagine you want to implement a sort, but rather than a defined and consistent comparator, the comparison uses a heuristic of some sense - so it's not a guarantee it will be correct. An example might be analogous to how eye doctors identify your prescription. They show two prescriptions and ask which is better. In some cases, as a patient you might not answer correctly for two close values. For values that are far apart, you will be more accurate.
If for example, you want to compare numeric values, you might model this as a custom comparator like:
public class HeuristicComparator implements Comparator {
@Override
public int compare(double val1, double val2) {
double adjustedVal1 = val1 + Math.random();
double adjustedVal2 = val2 + Math.random();
return Double.compare(adjustedVal1, adjustedVal2);
}
}
In this basic example, I arbitrarily assigning some random variation to the comparison operation, effectively saying that any double values less than 1.000 apart might be sorted incorrectly. 1.5 might be less than 1.3, but only some of the time.
What other strategies are there for modeling heuristic behavior like this rather than a comparator? It seems you could modify the sort logic too (perhaps skip random points, modify a sort to not "finish" all adjacent sorts)? What sorting algorithms that can be easily modified to match this behavior?
Or would it always be preferable to modify the comparator?