Yes, you can create an interface by setting a "sort" method for example, and each algorithm will implement this interface and define the way you sort in the "sort" method you defined in the interface.
Once you've done this, you'll 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 polymorphism concept well.
UPDATE
Using the functional approach, the same result can be obtained as follows:
Unsubscribing the method to receive a Consumer:
public static double timeToSelectionSort(Double[] arrayOfNumbers, Consumer<Double[]> consumer) {
And invoking the apply method of the consumer class as follows:
consumer.accept(arrayOfNumbers);
In 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;
}
In this way, it is enough that the signature of your sort methods accept an array of double as a parameter and they will be able to use your method, for example:
timeToSelectionSort(arrayOfNumbers, Selection::sort);
Assuming that the selection sort method signature is:
public class Selection {
public static void sort(Double[] arrayOfNumbers) {}
}