Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
- }
Add Comment
Please, Sign In to add comment