Prolog Quicksort using second element as a pivot

后端 未结 1 346
醉酒成梦
醉酒成梦 2021-01-22 21:46

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

相关标签:
1条回答
  • 2021-01-22 22:20

    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.
    
    0 讨论(0)
提交回复
热议问题