Created
April 27, 2019 18:33
-
-
Save tonyonodi/9538133aa8c8869fd3b6e09250096454 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const head = <A>(l: A[]) => l[0]; | |
const tail = <A>(l: A[]) => l.slice(1); | |
const splitList = <A>(l: A[]) => [l.slice(0, l.length / 2), l.slice(l.length / 2)]; | |
export const mergeSortedLists = (a: number[], b: number[], accumulator: number[] = []): number[] => { | |
if (a.length === 0) { | |
return [...accumulator, ...b]; | |
} | |
if (b.length === 0) { | |
return [...accumulator, ...a]; | |
} | |
return mergeSortedLists( | |
head(a) <= head(b) ? tail(a) : a, | |
head(a) > head(b) ? tail(b) : b, | |
[...accumulator, Math.min(head(a), head(b))] | |
); | |
}; | |
export const mergesort = (l: number[]): number[] => | |
l.length <= 1 | |
? l | |
: mergeSortedLists( | |
...(splitList(l).map(mergesort) as [number[], number[]]) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment