How to pass an algorithm as a parameter in java?

2

I've been doing some time measurements on sorting algorithms, and I've created this method that calculates how long an algorithm takes to sort an array of disordered numbers

public static double timeToSelectionSort(Double[] arrayOfNumbers) {

      double timeToSelectionSort =0;
  Stopwatch stopwatch = new Stopwatch();

  Selection.sort(arrayOfNumbers);

  timeToSelectionSort = stopwatch.elapsedTime(); 

  return   timeToSelectionSort;
  }

The problem is that I have to create this method for all the algorithms I want to use (mergesort, quicksort, insertionsort ...) Is there any way to pass these algorithms as parameters instead of copying this code whenever you want to test for another algorithm?

    
asked by anonymous 23.04.2017 / 03:13

1 answer

6

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) {}
}
    
23.04.2017 / 03:49