binsearch::[Int]->Int->Bool binsearch [x] y | x == y = True | otherwise = False binsearch xs y = if y == xs !! ( (length xs ) `div` 2 ) then True else if y < xs !! ( (length xs ) `div` 2 ) then binsearch (take ( (length xs ) `div` 2) xs) y else binsearch ( drop ( (length xs ) `div` 2) xs) y
上面的方法不能给出目标所在的索引,所以改写了一下
binsearch::[Int]->Int->Int->Int->Int binsearch xs a b y = if y < xs !! a then -1 else if y > xs !! b then -2 else if y == xs !! b then b else if y == xs !! ( (a + b ) `div` 2 ) then (a + b) `div` 2 else if y < (xs !! ( (a + b) `div` 2 )) then binsearch xs a ((a+b) `div` 2) y else binsearch xs ((a+b) `div` 2) b y