From 0d7d234931e1d19a72eb8bdede78ca736441d074 Mon Sep 17 00:00:00 2001 From: "Anders B. Clausen" Date: Tue, 27 Oct 2020 13:04:50 +0100 Subject: [PATCH] Added custom Insertion Sort algorithm, implemented in Haskell --- .../Sorting-Algorithms/InsertionSort.hs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Haskell/Algorithms/Sorting-Algorithms/InsertionSort.hs diff --git a/Haskell/Algorithms/Sorting-Algorithms/InsertionSort.hs b/Haskell/Algorithms/Sorting-Algorithms/InsertionSort.hs new file mode 100644 index 00000000..f6c1db15 --- /dev/null +++ b/Haskell/Algorithms/Sorting-Algorithms/InsertionSort.hs @@ -0,0 +1,20 @@ +-- # Insertion Sort in Haskell +-- This is an implementation of simple Insertion Sort in Haskell on any type that can be ordered. +-- Insertion Sort is a slow, but simple sorting algorithm that has time complexity O(n^2) + +-- Insert element into list in order, returning sorted list +insert :: (Ord a) => a -> [a] -> [a] +insert e [] = [e] +insert e (x:xs) + | e < x = e : x : xs + | otherwise = x : insert e xs + +-- Insertion sort on list, returning the list sorted +insertionSort :: (Ord a) => [a] -> [a] +insertionSort [] = [] +insertionSort (x:xs) = insert x (insertionSort xs) + +main :: IO () +main = do + let intList = [1, 30, 7, 10, 4, 25] + print $ insertionSort intList -- Returning [1,4,7,10,25,30] \ No newline at end of file