I'm trying to implement Quicksort in Prolog using the last element as pivot but somehow my predicate gets into an infinite loop. I'm using an accumulator to determine the part sorted so far (which in the end should be equal to the sorted list S that it should be looking for).
quicksort([], S, S).
quicksort(L, S, A ) :-
lastElement(L, P), /*last element P as pivot*/
split(L, P, Greater, Smaller), /* splits L into set Greater (than) and Smaller (than) by pivot P */
quicksort(Greater, Greater_S, A), /* require Greater to be sorted as well, calling this Greater_S */
quicksort(Smaller, S, [P|Greater_S]). /* same for Smaller, but accumulator should already have P and Greater_S sorted -> [P|Greater_S] as accumulator */
quicksort(L, S) :-
quicksort(L, S, []).
Somehow in quicksort(G, G_S, A)
, the list G_S
seems to iteratively increase in size with the same element, i.e. [X, X, X, X, ...]
.
What am I doing wrong?
If anyone could help me out it'd be much appreciated!
Thanks in advance.
EDIT: Definitions of the predicates split/4
and lastElement/2
:
lastElement([X], X).
lastElement([_|T], X) :- lastElement(T, X).
split([], _, [], []).
split([H|T], P, G, K) :-
H > P,
G = [H|T_],
split(T, P, T_, K).
split([H|T], P, G, K) :-
H =< P,
K = [H|T_],
split(T, P, G, T_).
deel/4
has the pivot as the last element, right? Anyway, what is this accumulator for, exactly? – user1812457lastElement/2
anddeel/4
! – falsecons
pairs). – user1812457