Sorting algorithms/Bubble sort: Difference between revisions
Content added Content deleted
m (Whitespace removal) |
(→{{header|Clojure}}: Clojure bubble sort, the most un-functional Clojure code I've written...) |
||
Line 341: | Line 341: | ||
Start = bsort {x \\ x <- [100,99..1]}</lang> |
Start = bsort {x \\ x <- [100,99..1]}</lang> |
||
=={{header|Clojure}}== |
|||
Bubble sorts a Java ArrayList in place. Uses 'doseq' iteration construct with a short-circuit when a pass didn't produce any change, and within the pass, an atomic 'changed' variable that gets reset whenever a change occurs. |
|||
<lang clojure> |
|||
(import 'java.util.ArrayList) |
|||
(defn bubble-sort |
|||
([arr] (bubble-sort compare arr)) |
|||
([cmp #^ArrayList arr] |
|||
(letfn [(swap! |
|||
[i j] |
|||
(let [t (.get arr i)] |
|||
(doto arr |
|||
(.set i (.get arr j)) |
|||
(.set j t)))) |
|||
(sorter |
|||
[stop-i] |
|||
(let [changed (atom false)] |
|||
(doseq [i (range stop-i)] |
|||
(if (> (cmp (.get arr i) (.get arr (inc i))) 0) |
|||
(do |
|||
(swap! i (inc i)) |
|||
(reset! changed true)))) |
|||
@changed))] |
|||
(doseq [stop-i (range (dec (.size a)) -1 -1) |
|||
:while (sorter stop-i)]) |
|||
arr))) |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
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 |