Created
October 21, 2012 22:18
-
-
Save skatenerd/3928714 to your computer and use it in GitHub Desktop.
binary search
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
(ns search.core | |
(:use clojure.test)) | |
(defn truncated-half-count [items] | |
(int (/ (count items) 2))) | |
(defn middle-index [items] | |
(truncated-half-count items)) | |
(defn middle-item [items] | |
(nth items (middle-index items))) | |
(defn drop-half [items] | |
(drop (truncated-half-count items) items)) | |
(defn take-half [items] | |
(take (truncated-half-count items) items)) | |
(defn filtered-items [items function target] | |
(let [middle-value (function (middle-item items))] | |
(cond | |
(= middle-value target) | |
(list (middle-item items)) | |
(> middle-value target) | |
(take-half items) | |
(< middle-value target) | |
(drop-half items)))) | |
(defn binary-search [items function target] | |
(if (= 1 (count items)) | |
(first items) | |
(binary-search (filtered-items items function target) function target) | |
)) | |
(defn -main [] | |
(is (= 3 (binary-search (range 10) identity 3))) | |
(is (= 3 (binary-search (range 11) identity 3))) | |
(is (= 2 (binary-search (range 20) #(* 2 %) 4))) | |
(is (= 2 (binary-search (range 21) #(* 2 %) 4)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment