I’ve found such an example of naive sort written in prolog and I am trying to understand it:
naive_sort(List,Sorted):-perm(List,Sorted),is_sorted(Sorted).
is_sorted([]).
is_sorted([_]).
is_sorted([X,Y|T]):-X=<Y,is_sorted([Y|T]).
perm(List,[H|Perm]):-delete(H,List,Rest),perm(Rest,Perm).
perm([],[]).
delete(X,[X|T],T).
delete(X,[H|T],[H|NT]):-delete(X,T,NT).
Naive_sort call works correctly but I just can’t figure out why. The main problem is the permutation. When it is called implicitly it always returns only one value. How is it then possible that in naive_sort function call all permutations are checked? Also how could I modify perm function to write all permutations?
This is truly a naive sort — it traverses the tree of all possible permutations until it luckily finds a sorted one. That’s have a complexity of O(n!) i presume :>
About the permutation function — it works “backwards” — note that the definition takes the head out of the result. If you turn around your point of view, you’ll notice that instead of deleting it actually inserts values by working backwards. As the algorithm is working backwards, hence the
Head chosen may be anything that will allow a result to be created, hence any unused value from List.Basically the permutation algorithm translates to the following procedural implementation:
This way you generate permutations. All of them.
In short – perm generates the whole space of possible solutions by starting out of an empty solution and checking how the given solution is possible from a valid delete.