Sorting algorithms/Bubble sort: Difference between revisions

→‎{{header|Clojure}}: fixed compilation error due to typo; small improvements; added example invocation
(→‎{{header|Oz}}: added functional version)
(→‎{{header|Clojure}}: fixed compilation error due to typo; small improvements; added example invocation)
Line 344:
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 lispclojure>(importns 'java.util.ArrayList)bubblesort
(:import java.util.ArrayList))
 
(defn bubble-sort
"Sort in-place.
arr must implement the Java List interface and should support
random access, e.g. an ArrayList."
([arr] (bubble-sort compare arr))
([cmp #^ArrayList arr]
(letfn [(swap! [i j]
(let [it j(.get arr i)]
(let [t (.getdoto arr i)]
(.set i (.get arr j))
(doto arr
(.set i (.get arrset j t))))
:while (sorter [stop-i)])
(.set j t))))
(let [changed (atom false)]
(sorter
(doseq [i (range stop-i)]
(if (pos? (cmp (.get arr i) (.get arr (inc i))))
(let [changed (atom false)]
(do
(doseq [i (range stop-i)]
(if (> (cmp (.get arr i) (.getswap! arri (inc i))) 0)
(reset! changed true))))
(do
(swap! i (inc i @changed))]
(reset!doseq changed[stop-i true)(range (dec (.size arr)) -1 -1)
:while (sorter stop-i)])
@changed))]
arr)))
(doseq [stop-i (range (dec (.size a)) -1 -1)
 
:while (sorter stop-i)])
(println (bubble-sort (ArrayList. [10 9 8 7 arr6 5 4 3 2 1])))</lang>
 
=={{header|Common Lisp}}==
Bubble sort an sequence in-place, using the < operator for comparison if no comaprison function is provided
Anonymous user