序言中的选择排序 [英] Selection sort in prolog

查看:52
本文介绍了序言中的选择排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Prolog 的新手,我正在尝试进行选择排序.这是我所拥有的:

I'm new in Prolog and I'm trying to make the selection sort. Here is what I have:

ssort([],[]).
ssort([M|S],L):-min(M,L),remove(M,L,N),ssort(S,N).

min(M,[M]).
min(M,[H,T]):-min(N,T),min2(M,H,N).

min2(A,A,B):-less(A,B).
min2(B,A,B):-not(less(A,B)).

less(A,B):-(A<B).

append([],B,B).
append([H|A],B,[H|AB]):-append(A,B,AB).

remove(X,L,N):-append(A,[X|B],L),append(A,B,N).

但是当我尝试这样做时:

But when I try this for example:

ssort(S,[5,3,1]),write(S).

我得到 false,无论我尝试什么.你能告诉我如何对列表进行排序并得到用 S 编写的结果吗?

I get false, no matter what I try. Can you tell me how can I actually sort the list and get the result written in S?

推荐答案

正如@Boris 所指出的,主要错误是在 min/2 谓词中,因为它需要第三个参数才能返回该参数中的 min 元素.经过一些小的更改,代码如下所示:

As well pointed out by @Boris the main mistake was in min/2 predicate because it needs a 3rd parameter in order to return the min element in that parameter. With a few small changes the code looks like:

ssort([],[]).
ssort([M1|S],[H|T]):-min(H,T,M1),remove(M1,[H|T],N),ssort(S,N).

min(M,[],M).
min(M,[H|T],M1):-min2(M,H,N),min(N,T,M1).

min2(A,B,A):-less(A,B).
min2(A,B,B):-not(less(A,B)).

less(A,B):-(A<B).

append([],B,B).
append([H|A],B,[H|AB]):-append(A,B,AB).

remove(X,L,N):-append(A,[X|B],L),append(A,B,N).

示例:

?- ssort(S,[5,3,1]).
S = [1, 3, 5] ;
false.

?- ssort(S,[5,3,1,7]).
S = [1, 3, 5, 7] ;
false.

<小时>

正如@Will Ness 正确指出的那样,唯一的错误是 min(M,[H,T]) 中的逗号,因此更改为 min(M,[H|T]) 可以正常工作!!!.我认为 min/2 谓词不能很好地工作,所以我在上面的答案中更改了它,但最终这不是必需的.

As @Will Ness correctly pointed out the only mistake was the comma in min(M,[H,T]) so changing to min(M,[H|T]) it works fine!!!. I thought that min/2 predicate wasn't working very well so I changed it in the answer above but finally this was not necessary.

这篇关于序言中的选择排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆