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 th
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.