btholt / complete-intro-to-computer-science

Complete Intro to Computer Science, as taught by Brian Holt for Frontend Masters
https://frontendmasters.com/courses/computer-science-v2/
Other
330 stars 259 forks source link

better merge func for merge sort #17

Open always-maap opened 3 years ago

always-maap commented 3 years ago

shifting array make it reindex the array. is n't it a better solution ?

const mergeArr = (arr1, arr2) => {
  const mergedArr = [];
  let arr1Idx = 0,
    arr2Idx = 0;
  while (arr1Idx < arr1.length && arr2Idx < arr2.length) {
    if (arr1[arr1Idx] > arr2[arr2Idx]) {
      mergedArr.push(arr2[arr2Idx]);
      arr2Idx++;
    } else {
      mergedArr.push(arr1[arr1Idx]);
      arr1Idx++;
    }
  }
  while (arr1Idx < arr1.length) {
    mergedArr.push(arr1[arr1Idx]);
    arr1Idx++;
  }
  while (arr2Idx < arr2.length) {
    mergedArr.push(arr2[arr2Idx]);
    arr2Idx++;
  }
  return mergedArr;
};

inspiration from introduction to algorithm v3