Guest User

Untitled

a guest
Dec 15th, 2017
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.74 KB | None | 0 0
  1. function mergeSort (arr) {
  2. function merge (l, m, r) {
  3. let i = 0, j = 0, k = l
  4.  
  5. const leftL = m - l + 1
  6. const rightL = r - m
  7.  
  8. const tempL = []
  9. const tempR = []
  10.  
  11. for (; i < leftL; i++)
  12. tempL[i] = arr[l + i]
  13.  
  14. for(; j < rightL; j++)
  15. tempR[j] = arr[m + 1 + j]
  16.  
  17. i = j = 0
  18.  
  19. while (i < leftL && j < rightL) {
  20. if (tempL[i] < tempR[j])
  21. arr[k++] = tempL[i++]
  22. else
  23. arr[k++] = tempR[j++]
  24. }
  25.  
  26. while (i < leftL)
  27. arr[k++] = tempL[i++]
  28.  
  29. while (j < rightL)
  30. arr[k++] = tempR[j++]
  31. }
  32.  
  33. function sort (l, r) {
  34. if (l < r) {
  35. const m = Math.floor((r + l) / 2)
  36.  
  37. sort(l, m)
  38. sort(m + 1, r)
  39.  
  40. merge(l, m, r)
  41. }
  42. }
  43.  
  44. sort(0, arr.length - 1)
  45. }
Add Comment
Please, Sign In to add comment