name = 'quick_sort/2' slug = 'sort a list using quicksort' description = '''\

quick_sort(L, SL): the list SL contains the elements of L sorted in non-decreasing order. Use the predicate pivoting/4 to implement quicksort.

?- quick_sort([2,3,1,5,4], L).
  L = [1,2,3,4,5].
''' plan = ['''\

Divide and conquer! And use previous solutions, of course. :)

''', '''\

Take the head away, use it as a pivot, divide the tail into smaller and larger elements. Use recursion on so obtained sublists since both are shorter (in the worst case scenario shorter by just the head element -- this also explains why quicksort works worst on already sorted lists). In the end simply combine the sublists.

''', '''\

If list L is composed of head P and tail T and if the tail is split into sublists containing smaller and larger elements, respectively, based on pivot P, and if we assume the recursion sorts these two sublists into lists SortedSmallerElems and SortedGreaterElems, and if finally we concatenate these two lists and add in between pivot/head P, then this results in correctly sorted initial list L.

'''] hint = { 'eq_instead_of_equ': '''\

The operator == is "stricter" than operator = in the sense that for the latter it is enough to be able to make the two operands equal (unification).

Of course, you can also solve the exercise without explicit use of either of these two operators, just remember that unification is implicitly performed with the predicate's arguments (head of clause).

''', 'eq_instead_of_equ_markup': '''\

Perhaps the operator for unification (=) would be better?

''', 'base_case': '''\

Did you think of a base case? Which list can you sort without any effort whatsoever?

''', 'recursive_case': '''\

The base case is ok. However, what about the general recursive case?

''', 'predicate_always_false': '''\

It seems your predicate is always "false". Did you give it the correct name, or is it perhaps misspelled?

If the name is correct, check whether something else is misspelled, perhaps there is a full stop instead of a comma or vice versa, or maybe you typed a variable name in lowercase?

It is, of course, also possible that your conditions are too restrictive, or even impossible to satisfy (as would be, for example, the condition that X is simultaneously smaller and greater than Y, or something similarly impossible).

''', 'timeout': '''\

Is there an infinite recursion at work here? How will it ever stop?

Or perhaps is there a missing, faulty, or simply incompatible (with the general recursive case) base case?

''', 'arbitrary_base_case': '''\

How can the sorted list be anything whatsoever or a list with an arbitrary element? Did you use a variable without an assigned value?

''', 'forgotten_pivot': '''\

Did you, perhaps, forgot to put the pivot element back into the list when returning from recursion?

''', }