Prolog Quicksort using second element as a pivot

ⅰ亾dé卋堺 提交于 2019-12-20 03:52:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!