Guest User

Untitled

a guest
Jun 22nd, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. // compare the arrays item by item and return the concatenated result
  2. function merge(left, right) {
  3. const result = [];
  4. let indexLeft = 0;
  5. let indexRight = 0;
  6.  
  7. while (indexLeft < left.length && indexRight < right.length) {
  8. if (left[indexLeft] < right[indexRight]) {
  9. result.push(left[indexLeft]);
  10. indexLeft += 1;
  11. } else {
  12. result.push(right[indexRight]);
  13. indexRight += 1;
  14. }
  15. }
  16.  
  17. return result.concat(left.slice(indexLeft)).concat(right.slice(indexRight));
  18. }
  19.  
  20. // Split the array into halves and merge them recursively
  21. function mergeSort(arr) {
  22. if (arr.length === 1) {
  23. // return once we hit an array with a single item
  24. return arr;
  25. }
  26.  
  27. const middle = Math.floor(arr.length / 2); // get the middle item of the array rounded down
  28. const left = arr.slice(0, middle); // items on the left side
  29. const right = arr.slice(middle); // items on the right side
  30.  
  31. return merge(
  32. mergeSort(left),
  33. mergeSort(right),
  34. );
Add Comment
Please, Sign In to add comment