I'm implementing (single-pivot) Quicksort in Java.
I read there is a term of partitioning and I thought I can write a method with extensibility.
public static <E> void sort(
final List<? extends E> list,
final Comparator<? super E> comparator,
final BiFunction<List<? extends E>, Comparator<? super E>, Integer> partitioner) {
if (list.size() < 2) {
return;
}
final int p = partitioner.apply(list, comparator);
sort(list.subList(0, p), comparator, partitioner);
sort(list.subList(p + 1, list.size()), comparator, partitioner);
}
It seemed good to me. The original intention is giving a chance to select any partitioning logic with the BiFunction
which takes the unsorted list and the comparator and returns the partitioning index.
And I tried to add another method for Lomuto partition scheme.
static <E> void lomuto(final List<? extends E> list,
final Comparator<? super E> comparator) {
sort(list,
comparator,
(l, c) -> {
final E pivot = l.get(l.size() - 1);
int i = 0;
for (int j = 0; j < l.size() - 1; j++) {
if (c.compare(l.get(j), pivot) <= 0) {
swap(l, j, i++);
}
}
swap(l, l.size() - 1, i);
return i;
});
}
And the compiler complains at c.compare(l.get(j), pivot)
part.
Required type Provided
o1: capture of ? super capture of ? extends E E
o2: capture of ? super capture of ? extends E E
I found I can work around with
static <E> void lomuto(final List<E> list, final Comparator<? super E> comparator) {
How can I still do the PECS with lomuto
method? ? extends E
?