Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Binary search in Haskell (#5728)
Browse files Browse the repository at this point in the history
Co-authored-by: Riyazul555 <riyazulislam2003@gmail.com>
Co-authored-by: Anandha Krishnan S <anandajith@gmail.com>
  • Loading branch information
3 people authored Jun 25, 2024
1 parent bcd7257 commit 01f39ac
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions program/program/implement-binary-search/implement_binary_search.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
-- Binary search function
binarySearch :: (Ord a) => [a] -> a -> Int
binarySearch arr x = binarySearchHelper arr x 0 (length arr - 1)

-- Helper function to perform the binary search
binarySearchHelper :: (Ord a) => [a] -> a -> Int -> Int -> Int
binarySearchHelper arr x lowerBound upperBound
| upperBound < lowerBound = -1 -- x does not exist
| arr !! midPoint < x = binarySearchHelper arr x (midPoint + 1) upperBound
| arr !! midPoint > x = binarySearchHelper arr x lowerBound (midPoint - 1)
| otherwise = midPoint -- x found at midPoint
where
midPoint = lowerBound + (upperBound - lowerBound) `div` 2

-- Example usage
main :: IO ()
main = do
let arr = [2, 3, 4, 10, 40]
let x = 10
let result = binarySearch arr x
if result /= -1
then putStrLn $ "Element " ++ show x ++ " is present at index " ++ show result
else putStrLn $ "Element " ++ show x ++ " is not present in array"

0 comments on commit 01f39ac

Please sign in to comment.