Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

better merge func for merge sort #17

Open
always-maap opened this issue Jun 18, 2021 · 0 comments
Open

better merge func for merge sort #17

always-maap opened this issue Jun 18, 2021 · 0 comments

Comments

@always-maap
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant