Created
November 1, 2013 07:46
-
-
Save pyrocat101/7262081 to your computer and use it in GitHub Desktop.
bisect-left in Clojure
This file contains 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-gte | |
[items value] | |
(letfn | |
[(do-search | |
[low high] | |
(if (< low high) | |
(let [mid (quot (+ low high) 2)] | |
(if (> value (items mid)) | |
(recur (inc mid) high) | |
(recur low mid))) | |
low))] | |
(do-search 0 (count items)))) | |
(binary-search-gte [] 42) | |
(binary-search-gte [1 2] 3) | |
(defn linear-search | |
[items value] | |
(letfn | |
[(do-search | |
[items index] | |
(cond | |
(empty? items) -1 | |
(= value (first items)) index | |
:else (recur (rest items) (inc index))))] | |
(do-search items 0))) | |
(let | |
[xs (into [](->> (repeatedly (fn [] (int (* (rand) 100)))) (take 1000) (sort)))] | |
(every? #(= (linear-search xs %) | |
(binary-search-gte xs %)) | |
xs)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment