Search code examples
javascriptwhile-loopmergesort

JavaScript while loop is being skipped when condition is evaluated true


As the title said... I practiced creating merge sort function. it seems that the merge function just skip the second or third while loop (witch adding the rest of the numbers if one of the arrays is empty).

The ri < ri.length condition is evaluated to be true but the while loop is skipped.

function mergeSort(array) {
  console.log("Array length", array.length);
  if (array.length === 1)
    return array;

  const middle = Math.floor(array.length / 2);
  const right = array.slice(middle, array.length);
  const left = array.slice(0, middle);

  let leftSorted = mergeSort(left);
  let rightSorted = mergeSort(right);
  let merged = merge(leftSorted, rightSorted);
  return merged;
}

function merge(left, right) {

  let ret = [];
  let li = 0,
    ri = 0;
  console.log("leftLength", left.length, "rightlength", right.length);
  while (li < left.length && ri < right.length) {
    console.log("li", li, "ri", ri)
    console.log("left[li]", left[li], "right[ri]", right[ri])
    if (left[li] < right[ri]) {
      console.log("pushing from left");
      ret.push(left[li]);
      li++;
    } else {
      console.log("pushing from right");
      ret.push(right[ri]);
      ri++;
    }
  }

  console.log("li", li, "leftLength", left.length, li < left.length);
  while (li < left.length) {

    console.log("pushing from left");
    ret.push(left[li]);
    li++;
  }

  console.log("ri", ri, "rightLength", right.length, ri < right.length);
  while (ri < right.length) {

    console.log("pushing from right");
    ret.push(right[ri]);
    ri = ri + 1;
  }

  return ret;
}

const list = [2, 5, 1, 3, 7, 2, 3, 8, 6, 3]
console.log(mergeSort(list)) // [ 1, 2, 2, 3, 3, 3, 5, 6, 7, 8 ]


Solution

  • There is a typo on your while condition : lenght to length