Last active
December 14, 2017 08:47
-
-
Save alexnoz/3cd54a2544a652c39432ea74a1a16fd5 to your computer and use it in GitHub Desktop.
The merge sorting algorithm (in place version)
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
function mergeSort (arr) { | |
function merge (l, m, r) { | |
let i = 0, j = 0, k = l | |
const leftL = m - l + 1 | |
const rightL = r - m | |
const tempL = [] | |
const tempR = [] | |
for (; i < leftL; i++) | |
tempL[i] = arr[l + i] | |
for(; j < rightL; j++) | |
tempR[j] = arr[m + 1 + j] | |
i = j = 0 | |
while (i < leftL && j < rightL) { | |
if (tempL[i] < tempR[j]) | |
arr[k++] = tempL[i++] | |
else | |
arr[k++] = tempR[j++] | |
} | |
while (i < leftL) | |
arr[k++] = tempL[i++] | |
while (j < rightL) | |
arr[k++] = tempR[j++] | |
} | |
function sort (l, r) { | |
if (l < r) { | |
const m = Math.floor((r + l) / 2) | |
sort(l, m) | |
sort(m + 1, r) | |
merge(l, m, r) | |
} | |
} | |
sort(0, arr.length - 1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment