Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
update example solution (no explicit recursion, passes new tests)
Browse files Browse the repository at this point in the history
tasxatzial committed Jun 5, 2024

Verified

This commit was signed with the committer’s verified signature.
Robbepop Robin Freyler
1 parent 3e7962d commit 0a2d38b
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions exercises/practice/binary-search/.meta/src/example.clj
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
(ns binary-search)

(defn middle [alist]
(-> alist (count) (quot 2)))

(defn search-for
[elem alist]
(let [middle (middle alist)
cur-elem (nth alist middle)]
(cond
(= cur-elem elem) middle
(or (= middle (count alist)) (zero? middle)) (throw (Exception. (format "%s not found in list" elem)))
(< cur-elem elem) (+ middle (search-for elem (drop middle alist)))
(> cur-elem elem) (search-for elem (take middle alist)))))
[n coll]
(let [coll (vec coll)]
(loop [low-idx 0
high-idx (dec (count coll))]
(if (> low-idx high-idx)
(throw (Exception. "not found"))
(let [mid-index (quot (+ high-idx low-idx) 2)
mid-item (get coll mid-index)]
(cond
(= n mid-item) mid-index
(> mid-item n) (recur low-idx (dec mid-index))
:else (recur (inc mid-index) high-idx)))))))

0 comments on commit 0a2d38b

Please sign in to comment.