-
-
Notifications
You must be signed in to change notification settings - Fork 161
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Loading status checks…
update example solution (no explicit recursion, passes new tests)
1 parent
3e7962d
commit 0a2d38b
Showing
1 changed file
with
12 additions
and
11 deletions.
There are no files selected for viewing
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
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))))))) |