Last active
January 26, 2020 10:40
-
-
Save alldayalone/d160c8da2375b11f5682cc567209a274 to your computer and use it in GitHub Desktop.
Merge Sort
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
function merge(a, b) { | |
var result = []; | |
var i = 0; | |
var j = 0; | |
while(i + j < a.length + b.length) { | |
if (j >= b.length || a[i] <= b[j]) { | |
result.push(a[i]); | |
i++; | |
} else { | |
result.push(b[j]); | |
j++; | |
} | |
} | |
return result; | |
} | |
function sort(input) { | |
if (input.length < 2) { | |
return input; | |
} | |
var half = Math.floor(input.length / 2); | |
return merge( | |
sort(input.slice(0, half)), | |
sort(input.slice(half)) | |
); | |
} | |
// [0, 1, 2, 2, 4, 4, 4, 5, 5, 7, 8, 8, 78] | |
console.log(sort([4, 5, 2, 78, 8, 0, 2, 5, 7, 1, 4, 8, 4])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment