Created
December 5, 2020 13:23
-
-
Save gsrai/80521aa86020a67128e9827d413b5e99 to your computer and use it in GitHub Desktop.
Binary Search in Clojure
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 [n coll] | |
(loop [upper (dec (count coll)) | |
lower 0] | |
(let [mid (int (Math/ceil (/ (+ upper lower) 2)))] | |
(if (= upper lower) | |
nil | |
(cond (= n (nth coll mid)) mid | |
(< n (nth coll mid)) (recur (dec mid) lower) | |
(>= n (nth coll mid)) (recur upper mid)))))) | |
(binary-search 490 (vec (range 1 50))) | |
(binary-search 49 (vec (range 1 50))) | |
(binary-search 2 (vec (range 1 50))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment