-
Notifications
You must be signed in to change notification settings - Fork 394
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added custom Insertion Sort algorithm, implemented in Haskell
- Loading branch information
Anders B. Clausen
committed
Oct 27, 2020
1 parent
8a432bb
commit 0d7d234
Showing
1 changed file
with
20 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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] |