All files / sorts MergeSort.js

0% Statements 0/24
0% Branches 0/13
0% Functions 0/3
0% Lines 0/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                                                                                                                                         
/* eslint-disable no-param-reassign */
 
/**
 * Sorting Algorithm MergeSort
 *
 * Implementation based on pseudocode from Wikipedia.
 *
 * @author Bernhard Frick
 * @param {number[]} elements
 * @param {boolean} testing Set to true to test the algorithm
 * @return {number[] || {do: {}[], undo: {}[]}[]}
 */
export default function MergeSort(elements, testing = false) {
  const steps = [];
 
  const input = Array.from(elements);
 
  if (input.length === 0) {
    return testing ? input : steps;
  }
 
  /**
   * @param {number[]} leftArr
   * @param {number[]} rightArr
   * @return {number[]}
   */
  function merge(leftArr, rightArr) {
    const sortedArr = [];
 
    while (leftArr.length && rightArr.length) {
      if (leftArr[0] <= rightArr[0]) {
        sortedArr.push(leftArr[0]);
        leftArr = leftArr.slice(1);
      } else {
        sortedArr.push(rightArr[0]);
        rightArr = rightArr.slice(1);
      }
    }
 
    while (leftArr.length) {
      sortedArr.push(leftArr.shift());
    }
 
    while (rightArr.length) {
      sortedArr.push(rightArr.shift());
    }
 
    return sortedArr;
  }
 
  /**
   * @param {number[]} arr
   * @return {number[]}
   */
  function mergesort(arr) {
    if (arr.length < 2) {
      return arr;
    }
    const midpoint = Math.trunc(arr.length / 2);
    const leftArr = arr.slice(0, midpoint);
    const rightArr = arr.slice(midpoint, arr.length);
    return merge(mergesort(leftArr), mergesort(rightArr));
  }
 
  const output = mergesort(input);
 
  return testing ? output : steps;
}