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?
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 ).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With