Skip to content

Instantly share code, notes, and snippets.

@pyrocat101
Created November 1, 2013 07:46
Show Gist options
  • Save pyrocat101/7262081 to your computer and use it in GitHub Desktop.
Save pyrocat101/7262081 to your computer and use it in GitHub Desktop.
bisect-left in Clojure
(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