Skip to content

Instantly share code, notes, and snippets.

@bitemyapp
Created July 12, 2013 23:22
Show Gist options
  • Save bitemyapp/5988564 to your computer and use it in GitHub Desktop.
Save bitemyapp/5988564 to your computer and use it in GitHub Desktop.
(defn binary-search
"Finds earliest occurrence of x in xs (a vector) using binary search."
([xs x]
(loop [l 0 h (unchecked-dec (count xs))]
(if (<= h (inc l))
(cond
(== x (xs l)) l
(== x (xs h)) h
:else nil)
(let [m (unchecked-add l (bit-shift-right (unchecked-subtract h l) 1))]
(if (< (xs m) x)
(recur (unchecked-inc m) h)
(recur l m)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment