Return to Snippet

Revision: 61157
at July 24, 2015 05:48 by rtperson


Updated Code
module BinarySearch where

import Control.Lens
import Data.Maybe

a :: [Int]
a = [6, 13, 14, 25, 33, 43, 51, 53, 64, 72, 84, 93, 95, 96, 97]

bsearch :: Int -> [Int] -> Maybe Int
bsearch _   [] = Nothing
bsearch key xs 
    | key < fromJust val = bsearch key (take (mid-1) xs)
    | key > fromJust val = bsearch key (drop (mid+1) xs)
    | otherwise = val
  where
    mid = floor ((fromIntegral $ (length xs) - 1) / 2)
    val = xs ^? ix mid

Revision: 61156
at November 30, 2012 14:16 by rtperson


Initial Code
module BinarySearch where

a :: [Int]
a = [6, 13, 14, 25, 33, 43, 51, 53, 64, 72, 84, 93, 95, 96, 97]

bsearch :: Int -> [Int] -> Int
bsearch _   [] = -1
bsearch key xs 
    | key < val = bsearch key (take (mid-1) xs)
    | key > val = bsearch key (drop (mid+1) xs)
    | otherwise = val
  where
    mid = floor ((fromIntegral $ (length xs) - 1) / 2)
    val = xs !! mid

Initial URL

                                

Initial Description
Improved version, using lenses instead of the dangerous (!!) operator for list access.

Initial Title
Binary Search in Haskell

Initial Tags

                                

Initial Language
Haskell