Sorting algorithms/Bubble sort: Difference between revisions

Content added Content deleted
No edit summary
(→‎Common Lisp: whitespace (parens; don't assume tabs=8); "from 0" unnecessary; use 1+, 1-; while not -> until)
Line 345: Line 345:
Bubble sort an sequence in-place, using the < operator for comparison if no comaprison function is provided
Bubble sort an sequence in-place, using the < operator for comparison if no comaprison function is provided


<lang lisp>(defun bubble-sort( sequence &optional( compare #'<))
<lang lisp>(defun bubble-sort (sequence &optional (compare #'<))
"sort a sequence (array or list) with an optional comparison function (< is the default)"
"sort a sequence (array or list) with an optional comparison function (cl:< is the default)"
(loop with sorted = nil while (not sorted) do
(loop with sorted = nil until sorted do
(setf sorted t)
(setf sorted t)
(loop for a from 0 below (- (length sequence) 1) do
(loop for a below (1- (length sequence)) do
(unless (funcall compare (elt sequence a) (elt sequence (+ a 1)))
(unless (funcall compare (elt sequence a)
(rotatef (elt sequence a) (elt sequence (+ a 1)))
(elt sequence (1+ a)))
(rotatef (elt sequence a)
(setf sorted nil)))))
(elt sequence (1+ a)))
(setf sorted nil)))))</lang>


<lang lisp>(bubble-sort (list 5 4 3 2 1))</lang>
; main

(bubble-sort (list 5 4 3 2 1))
</lang>


=={{header|D}}==
=={{header|D}}==