Skip to content

Instantly share code, notes, and snippets.

@Chouser
Created June 8, 2013 15:50
Show Gist options
  • Save Chouser/5735580 to your computer and use it in GitHub Desktop.
Save Chouser/5735580 to your computer and use it in GitHub Desktop.
;;** Multi-thread stochastic bubble sort **
;; an example of how to use refs
(defn fizzy-sort-init [coll]
(mapv #(ref (vector %)) coll))
(defn fizzy-sort-step [refs]
(let [i (rand-int (dec (count refs)))
[a b] (map #(nth refs %) (iterate inc i))
[a-val b-val] (map #(peek (deref %)) [a b])]
(when (> a-val b-val)
(dosync (alter a conj b-val))
(dosync (alter b conj a-val))
nil)))
(defn fizzy-sort-view [refs]
(mapv #(peek (deref %)) refs))
;; (def my-refs (fizzy-sort-init (reverse (range 30))))
;; (dothreads! #(fizzy-sort-step my-refs) :threads 100 :times 100)
;; (fizzy-sort-view my-refs)
;; ;=> [0 1 2 4 5 5 5 6 10 13 13 13 13 14 15 16 16 18 21 21 21 22 23 24 24 25 26 28 29 29]
(defn fizzy-sort-step-v2 [refs]
(let [i (rand-int (dec (count refs)))
[a b] (map #(nth refs %) (iterate inc i))
[a-val b-val] (map #(peek (deref %)) [a b])]
(when (> a-val b-val)
(dosync
(alter a conj b-val)
(alter b conj a-val))
nil)))
(defn fizzy-sort-step-v3 [refs]
(let [i (rand-int (dec (count refs)))
[a b] (map #(nth refs %) (iterate inc i))]
(dosync
(let [[a-val b-val] (map #(peek (deref %)) [a b])]
(when (> a-val b-val)
(alter a conj b-val)
(alter b conj a-val)
nil)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment