气泡以Prolog语言排序 [英] Bubble sort in Prolog language
本文介绍了气泡以Prolog语言排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须实现气泡排序功能(排序算法)。
I must implement the bubble sort function (the sorting algorithm).
我已经实现了 bubblesort
, 交换
,这是气泡排序
的帮助功能:
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)
bubblesort(T1,T2)
我在这个问题上停留了2个小时。有人知道我该怎么做吗?
I'm stuck on this question for 2 hours. Does anyone have an idea how I can do that?
推荐答案
直到交换过程没有变化,请继续交换。如果交换没有变化,则您已对列表进行了排序。
Until there is no change in swap procedure, keep swapping. If there was no change in swap then you have sorted list.
bubblesort ( List, SortedList) :-
swap ( List, List1 ), ! ,
bubblesort ( List1, SortedList) .
bubblesort ( List, List).
swap ( [ X, Y | Rest ], [ Y, X | Rest ] ) :-
X > Y, ! .
swap ( [ Z | Rest ], [ Z | Rest1 ] ) : -
swap (Rest, Rest1 ).
这篇关于气泡以Prolog语言排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文