POV-Ray : Newsgroups : povray.off-topic : FizzBuzz : Re: Binary search Server Time
4 Sep 2024 05:16:48 EDT (-0400)
  Re: Binary search  
From: Invisible
Date: 5 Jul 2010 04:09:56
Message: <4c319354$1@news.povray.org>
OK, 3rd time lucky: let's see if I can actually implement this thing 
correctly. :-P

find :: (Ord y) => (x -> y) -> y -> IArray x -> (Int,Int) -> Maybe x
find field target array (base,size)
   | size <  0 = error "invalid subrange size"
   | size == 0 = Nothing
   | size == 1 = if field (array ! base) == target then Just (array ! 
base) else Nothing
   | otherwise =
     let
       size2 = size `div` 2
       base2 = base + size2
     in
       case compare (field (array ! base2)) target of
         EQ -> Just (array ! base2)
         GT -> find field target array (base, size2)
         LT -> find field target array (base + size2, size - size2)

Now, finally, it should work. (But I've said that twice before already...)

Damnit, no wonder nobody loves me. :-(


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.