Yes, you can create an interface by defining a "Sort" method for example, and each algorithm will implement this interface and define its way of sorting in this "Sort" method that you defined in the interface.
Done this, you will rewrite your method as follows:
public static double timeToSelectionSort(SortInterface sorter, Double[] arrayOfNumbers) {
double timeToSelectionSort =0;
Stopwatch stopwatch = new Stopwatch();
sorter.sort(arrayOfNumbers);
timeToSelectionSort = stopwatch.elapsedTime();
return timeToSelectionSort;
}
And your classes that perform this Sort can be as shown below:
public class Mergesort implements SortInterface {}
public class Quicksort implements SortInterface {}
In this example you will be using the concept of polymorphism well.
UPDATE
Using the functional approach, the same result can be obtained as follows:
Claiming the signature of the method to receive a Consumer :
public static double timeToSelectionSort(Double[] arrayOfNumbers, Consumer<Double[]> consumer) {
And by invoking the apply method of the Consumer class as follows:
consumer.accept(arrayOfNumbers);
This way your final method would look like this:
public static double timeToSelectionSort(Double[] arrayOfNumbers, Consumer<Double[]> consumer) {
double timeToSelectionSort = 0;
Stopwatch stopwatch = new Stopwatch();
consumer.accept(arrayOfNumbers);
timeToSelectionSort = stopwatch.elapsedTime();
return timeToSelectionSort;
}
This way, it is enough that the signature of your Sort methods accept a double array as parameter and they will be able to use your method passing for example:
timeToSelectionSort(arrayOfNumbers, Selection::sort);
Assuming that the signature of the Selection Sort method is :
public class Selection {
public static void sort(Double[] arrayOfNumbers) {}
}
Only I have about 10 Sorts to use and each one is in its own class. Isn’t there another way? I cannot rewrite my method to use Consumer?
– Dantex
I updated the answer. Take a look!
– Roque Santos