Re: bubblesort

From: Alan Bal jeu (jeu_at_sympatico.deleteme.ca)
Date: 04/27/04


Date: Mon, 26 Apr 2004 18:27:10 -0400


> > Egad, I forgot the difference between the two -- and somewhere along
> > the way took to calling insertion sort "bubblesort".
> >
> > The "!" after the call to 'swap' still bothers me, however:
> >
> > bubblesort(List,Sorted) :-
> > swap(List,PartSorted),!,
> > bubblesort(PartSorted,Sorted).
> > bubblesort(L,L).
> >
> > swap([X,Y|Tail],[Y,X|Tail]):-
> > gt(X,Y).
> > swap([X,Y|Tail],[X|Rest]) :-
> > not( gt(X,Y) ),
> > swap([Y|Tail],Rest).
> >

This would be better, stylistically.

bubblesort(List,Sorted) :-
     swap(List,PartSorted),
     bubblesort(PartSorted,Sorted).

swap([X,Y|Tail],[Y,X|Tail]):-
     gt(X,Y), !.
swap([X,Y|Tail],[X|Rest]) :-
     not( gt(X,Y) ),
     swap([Y|Tail],Rest).