Created
July 12, 2013 23:22
-
-
Save bitemyapp/5988564 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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