I am trying to implement a functional version of the Quicksort algorithm. My professor asked me to keep this as the signature:
public static <T, R> List<T> myQuickSort(Function<List<T>, Boolean> trivial,
Function<List<T>, T> solve, Function<List<T>, R> divide,
Function<T, List<R>> combine, List<T> input)
I created an auxiliary class named Pair, which goes like this:
public class Pair {
List<Integer> first;
List<Integer> second;
Pair(List<Integer> f, List<Integer> s) {
first = f;
second = s;
}
public static Pair div(List<Integer> input) {
int pivot = (int) input.get(0);
List<Integer> a = new ArrayList<Integer>();
List<Integer> b = new ArrayList<Integer>();
for(int i=1; i<input.size(); i++) {
if(input.get(i) < pivot) {
a.add(input.get(i));
} else {
b.add(input.get(i));
}
}
return new Pair(a, b);
}
} I am almost done, but I cannot figure out how to work recursively on a single partition of my input array. I tried to act like this:
if(trivial.apply(input)) {
solve.apply(input);
} else {
output = myQuickSort(trivial, solve, divide, combine,
(List<T>) divide.apply(input).first);
output.add(input.get(0));
output.addAll(myQuickSort(trivial, solve, divide, combine,
(List<T>) divide.apply(input).second));
return output;
}
return output;
But I am now stuck. Can anyone of you please tell where I am wrong and/or how can I implement my solution better? Here is also the main, if it can help:
Function<List<Integer>, Boolean> trivial = (a) -> a.size()==1;
Function<List<Integer>, Pair> divide = (a) -> Pair.div(input);
Function<Pair, List<Integer>> combine =
(a) -> Stream.concat(a.first.stream(), a.second.stream()).
collect(Collectors.toList());
Function<List<Integer>, Integer> solve = (a) -> a.get(0);
ArrayList<Integer> output = myQuickSort(trivial, solve, divide, combine, input);
combine
wereFunction<R, List<T>>
. – Gene Jan 15 '18 at 3:22div
return a triple of lists rather than a pair:class SplitByPivot { List<T> equal, less, greater; }
(Don't forget that the pivot can occur more than once in the input.) I'm pretty sure the bug is in the way you're implicitly handling the pivot as a tricky special case in thePair
. Theequal
field will let you express the algorithm without tricks. – Gene Jan 15 '18 at 18:48R
is, not the method. Therefore, you can’t assume that it will always be aPair
. It’s not even clear how you managed to compile your code with the implicit assumption thatR
isPair
. You should discuss that weird signature with your professor first. – Holger Jan 16 '18 at 13:35