条件为true时跳过while循环的JavaScript

时间:2018-10-04 08:58:20

标签: javascript while-loop mergesort

正如标题所述...我练习了创建合并排序功能。 似乎合并功能只是跳过了第二个或第三个while循环(如果其中一个数组为空,则女巫将其余数字相加)。

ri

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 ]

1 个答案:

答案 0 :(得分:0)

您的一阵阵错字是:lenghtlength