1

I have written code in javascript trying to return a single sorted array by giving two sortedarray inputs.

function finalArray(arr1, arr2) {
  const mergedArray = [];
  if (arr1.length === 0) {
    return arr2;
  }
  if (arr2.length === 0) {
    return arr1;
  }
  let arr1Item = arr1[0];
  let arr2Item = arr2[0];
  let i = 1;
  let j = 1;

  while (arr1Item || arr2Item) {
    if (arr2Item === undefined || arr1Item < arr2Item) {
      mergedArray.push(arr1Item);
      arr1Item = arr1[i];
      i++;
    } else {
      mergedArray.push(arr2Item);
      arr2Item = arr2[j];
      j++;
    }
  }
  return mergedArray
}

console.log(finalArray([2, 6, 4, 10], [15, 1, 5, 33]));

Can anyone help with how to merge unsorted arrays?

11
  • arr2Item === "undefiend" will not work... Commented Apr 8, 2021 at 23:11
  • Yeah even though not woring arr2Item === undefined Commented Apr 8, 2021 at 23:13
  • 1
    Walk through your logic manually on paper. You will end up going through all of first array because they are all less than first element of second array. Then when no element is left from first array will just start pushing second array in it's existing order Commented Apr 8, 2021 at 23:26
  • 1
    You won't get past that 15 to see the 1 until first array is all done though. Then you are always comparing undefined to the next element in second array Commented Apr 8, 2021 at 23:33
  • 1
    So basically implementing Merge Sort, fair. Please state any unusual requirements like this up front, though. Commented Apr 8, 2021 at 23:34

2 Answers 2

2

Merge your two arrays first, then perform the sort?

const arr1 = [2, 6, 4, 10];
const arr2 = [10, 1, 5, 33];
const newArray = ([...arr1, ...arr2]);
newArray.sort(function(a,b){return a - b});
console.log(newArray);

Expected output: [1, 2, 4, 5, 6, 10, 10, 33]

Sign up to request clarification or add additional context in comments.

Comments

0

The problem is you are comparing every two pair of data and pushing smaller one. First try to sort each sub array without entering compare process for mixing. After the sub arrays are being sorted, then compare to each other.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.