问题
I've been trying to learn prolog and I want to use the second element of a list as the pivot of a quicksort.
I thought using [Head | [Pivot | Tail] ] as the input in the method would work, but then I was not sure where I could place "Head", the first element.
like this:
qsort([],[]):- !.
qsort([Head|[Pivot|Tail]],Sorted):-
split(Pivot,[Head|Tail],Less,Greater),
qsort(Less,SortedLess),
qsort(Greater,SortedGreater),
append(SortedLess,[Pivot|SortedGreater],Sorted).
split(_,[],[],[]).
split(Pivot,[X|T],[X|Less],Greater):-
X=<Pivot,split(Pivot,T,Less,Greater).
split(Pivot,[X|T],Less,[X|Greater]):-
X>Pivot,split(Pivot,T,Less,Greater).
However, when I try to sort the list with qsort([8, 3, 4, 12, 25, 4, 6, 1, 9, 22, 6], Sorted).
It simply returns false. What am I doing wrong?
回答1:
However, when I try to sort the list with
qsort([8, 3, 4, 12, 25, 4, 6, 1, 9, 22, 6], Sorted)
. It simply returns false. What am I doing wrong?
Eventually this algorithm will make calls with a list with exactly one element, and you did not define a qsort/2
clause that will match with that list.
You can resolve this by adding a rule:
qsort([],[]).
qsort([X], [X]).
qsort([Head, Pivot|Tail],Sorted):-
split(Pivot,[Head|Tail],Less,Greater),
qsort(Less,SortedLess),
qsort(Greater,SortedGreater),
append(SortedLess,[Pivot|SortedGreater],Sorted).
This gives us:
?- qsort([8, 3, 4, 12, 25, 4, 6, 1, 9, 22, 6], Sorted).
Sorted = [1, 3, 4, 4, 6, 6, 8, 9, 12|...] ;
false.
来源:https://stackoverflow.com/questions/59227028/prolog-quicksort-using-second-element-as-a-pivot