现在的位置: 首页 > 综合 > 正文

二分查找

2018年02月15日 ⁄ 综合 ⁄ 共 481字 ⁄ 字号 评论关闭

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
【上篇】
【下篇】

抱歉!评论已关闭.