Creating BubbleSort

Now, we can start creating the bubble sort that implements the Sort interface:

 ...
import java.util.Comparator;

public class BubbleSort implements Sort, SortSupport {
    @Override
    public void sort(Sortable collection) {
        var n = collection.size();
        while (n > 1) {
            for (int j = 0; j < n - 1; j++) {
                if (comparator.compare(collection.get(j),
                        collection.get(j + 1)) > 0) {
                    swapper.swap(j, j + 1);
                }
            }
            n--;
        }
    }
 ...

Normally, the algorithm needs two operations. We implemented those specific to a String arraycomparing two elements and swapping two elements. This time, however, the sort implementation itself does not know what type it should sort. It also does not know how the elements are stored. It can be an array, a list or something ...

Get Java Projects - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.