-
Notifications
You must be signed in to change notification settings - Fork 1
/
MergeSort.elm
56 lines (41 loc) · 1.36 KB
/
MergeSort.elm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
module MergeSort exposing (mergeSort, update, animate, view)
import Html exposing (Html)
import Point exposing (Point, updateStyles, updatePosition, animateElement, renderPoints)
import Animation
update : List Point -> List Point
update unsorted =
List.map updateStyles (List.indexedMap (\i -> updatePosition i) unsorted)
animate : Animation.Msg -> List Point -> List Point
animate time newList =
List.map (animateElement time) newList
view : List Point -> List (Html msg)
view list =
renderPoints "Merge Sort" list
mergeSort : List Point -> List Point
mergeSort unsorted =
if (List.length unsorted) <= 1 then
unsorted
else
let
middle =
(List.length unsorted) // 2
left =
List.take middle unsorted
right =
List.drop middle unsorted
in
merge (mergeSort left) (mergeSort right) []
merge : List Point -> List Point -> List Point -> List Point
merge left right sorted =
case left of
[] ->
sorted ++ right
x :: xs ->
case right of
[] ->
sorted ++ left
y :: ys ->
if x.value < y.value then
merge xs right (sorted ++ [ x ])
else
merge left ys (sorted ++ [ y ])