Skip to content

Merge sort README in Haskell #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
27 changes: 27 additions & 0 deletions merge-sort.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
-- # Binary Search in Haskell
-- This is an implementation of simple Binary Search in Haskell on any type that can be ordered.
-- Binary Search is an effective searching algorithm, that can be used to find an element in a sorted list in O(lg(n)) time.

-- Binary search with index carry
bsWithIndex :: (Ord a) => [a] -> a -> Int -> Maybe Int
bsWithIndex list n i
| n == head list = Just i
| len == 1 = Nothing -- only candidate in list is not the right elem
| n < head ys = bsWithIndex xs n i
| otherwise = bsWithIndex ys n (i + half)
where
len = length list
half = len `div` 2
(xs, ys) = splitAt half list

-- Binary search returning index, or -1 if element not in list
bs :: (Ord a) => [a] -> a -> Int
bs list n = case bsWithIndex list n 0 of
Just x -> x
Nothing -> -1

main :: IO ()
main = do
let intList = [1,4,7,10,25,30]
print $ bs intList 29 -- 29 -> -1 as not in list
print $ bs intList 7 -- 7 -> 2 as in list