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

Binary search in Haskell #5728

Merged
merged 2 commits into from
Jun 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"