Prolog语言中的冒泡排序
我必须实现冒泡排序功能(排序算法)。
我已经实现了bubblesort
和swap
,这是bubblesort
的帮助函数:
swap([X,Y|T1],[Y,X|T1]):-(Y<X,!).
swap([X|T1],[X|T2]):- swap(T1,T2).
bubblesort([],[]) :- !.
bubblesort(T1,T2) :- (bubblesort(swap(T1,T2),T2)).
我得到了一个无限循环。我必须保留函数的签名:
冒泡排序(T1,T2)
我在这个问题上停留了两个小时。有谁知道我该怎么做?
I must implement the bubble sort function (the sorting algorithm).
I have already implemented bubblesort
and swap
, a help function for bubblesort
:
swap([X,Y|T1],[Y,X|T1]):-(Y<X,!).
swap([X|T1],[X|T2]):- swap(T1,T2).
bubblesort([],[]) :- !.
bubblesort(T1,T2) :- (bubblesort(swap(T1,T2),T2)).
I get an infinite loop. I must keep the signature of the function:
bubblesort(T1,T2)
I'm stuck on this question for 2 hours. Does anyone have an idea how I can do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
直到交换过程没有变化为止,继续交换。如果交换没有变化,那么您已经对列表进行了排序。
Until there is no change in swap procedure, keep swapping. If there was no change in swap then you have sorted list.
写出如此低效的东西几乎是痛苦的:
It almost hurts to write something so inefficient:
简单的冒泡排序算法由两个主要循环组成:
内部循环 (1) 可以这样表示:
上面的
do_bubble_sort/2
接受一个列表,如果不满足=<
,则递归地交换列表中的连续元素。代码>测试(第三条)。然后,该内部循环由外部循环谓词bubble_sort/2
调用,如下所示:该谓词采用输入列表并递归应用
do_bubble_sort/2
直到谓词 < code>sorted_order/1 结果成功,即列表最终排序。sorted_order/1
可以这样定义:该谓词采用一个列表并递归地检查每对连续元素是否按排序顺序(通过
=<
测试,就像我们在do_bubble_sort/2
中使用的那样 - 这很重要,否则算法可能不会终止!)The simple bubble sort algorithm is made up of two main loops:
The inner loop (1) can be expressed like this:
do_bubble_sort/2
above takes a list, and recursively swaps consecutive elements along the list if they don't satisfy the=<
test (3rd clause). This inner loop is then called by the outer loop predicate,bubble_sort/2
, as shown below:This predicate takes the input list and recursively applies
do_bubble_sort/2
until the predicatesorted_order/1
succeeds on the result, i.e., if the list is eventually sorted.sorted_order/1
can be defined like this:This predicate takes a list and recursively checks that each pair of consecutive elements are in sorted order (by way of the
=<
test, just as we're using indo_bubble_sort/2
- this is important, otherwise the algorithm mightn't terminate!)该问题是由递归查询引起的。查询
冒泡排序(T1, T2)
时,它查询bubblesort(swap(T1, T2), T2),然后通过bubblesort/2的第二个子句,
bubblesort(swap(swap(T1, T2), T2'), T2)
和T2
统一为T2
,然后循环。它永远不会得到
swap(T1, T2)
查询的第一个结果。The problem was caused by recursive querying. When querying
bubblesort(T1, T2)
,it queries
bubblesort(swap(T1, T2), T2)
, then, by second clause ofbubblesort/2
,bubblesort(swap(swap(T1, T2), T2'), T2)
andT2
is unified asT2
, and then loop.It never get the first result of
swap(T1, T2)
query.