Advertisement
Guest User

Untitled

a guest
Mar 24th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. function mergeSort (array) {
  2. if (array.length === 1) {
  3. return array
  4. }
  5. // Split Array in into right and left
  6. const length = array.length;
  7. const middle = Math.floor(length / 2)
  8. const left = array.slice(0, middle)
  9. const right = array.slice(middle)
  10.  
  11. return merge(
  12. mergeSort(left),
  13. mergeSort(right)
  14. )
  15. }
  16.  
  17. function merge(left, right){
  18. const result = [];
  19. let leftIndex = 0;
  20. let rightIndex = 0;
  21. while(leftIndex < left.length &&
  22. rightIndex < right.length){
  23. if(left[leftIndex] < right[rightIndex]){
  24. result.push(left[leftIndex]);
  25. leftIndex++;
  26. } else{
  27. result.push(right[rightIndex]);
  28. rightIndex++
  29. }
  30. }
  31.  
  32. return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex));
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement