From 179607bdfe9ea36cf5325a10ee8b7edb1f834147 Mon Sep 17 00:00:00 2001 From: hackprot1 <91518230+hackprot1@users.noreply.github.com> Date: Sat, 2 Oct 2021 23:30:04 +0530 Subject: [PATCH] Merge sort README in Haskell --- merge-sort.hs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 merge-sort.hs diff --git a/merge-sort.hs b/merge-sort.hs new file mode 100644 index 00000000..8bcb192d --- /dev/null +++ b/merge-sort.hs @@ -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