Quantcast
Viewing latest article 4
Browse Latest Browse All 10

Implementing Binary Search with Clojure

I was trying to implement a simple binary search using a purely functional approach, and after much hacking, googling and wikibooking, came up with this in Clojure.

(defn binarysearch
  ([lst n]
      (binarysearch lst 0(dec (count lst)) n))
  ([lst lb ub n]
      (if(> lb ub)-1; this is the case where no element is found
          (let[mid (quot (+ lb ub)2)
                mth (nth lst mid)]
            (cond
             ; mid > n, so search lower
             (> mth n)(recur lst lb (dec mid) n)
             ; mid < n, search upper
             (< mth n)(recur lst (inc mid) ub n)

read more


Viewing latest article 4
Browse Latest Browse All 10

Trending Articles