How to pass an algorithm as parameter in java?

Asked

Viewed 94 times

2

I’m doing some time measurements on sorting algorithms and created this method that calculates the time it takes an algorithm 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 run tests to another algorithm?

1 answer

6


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?

  • I updated the answer. Take a look!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.