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

[Practice] Merge two sorted arrays #28

Open
lpatmo opened this issue Mar 2, 2019 · 4 comments
Open

[Practice] Merge two sorted arrays #28

lpatmo opened this issue Mar 2, 2019 · 4 comments

Comments

@lpatmo
Copy link
Member

@lpatmo lpatmo commented Mar 2, 2019

Given two sorted arrays, merge them together. 
Test cases:
merge([1, 3, 5,11],[2,4,6]) => [1,2,3,4,5,6,11]
merge([], [2,9,11]); => [2,9,11]
merge([1, 2, 3], []); => [1,2,3]
merge([]. []) => []
@lpatmo
Copy link
Member Author

@lpatmo lpatmo commented Mar 2, 2019

function mergeSorted(arr1,arr2) {
  let results = [];
  let i = 0, j = 0;
  while(i < arr1.length && j < arr2.length) {
    if (arr2[j] > arr1[i]) {
      results.push(arr1[i])
      i++;
    } else {
      results.push(arr2[j]);
      j++;
    }
  }
 //once we've exceeded the index on one of them (i.e. one array is longer than the other one)
  while (i < arr1.length) {
    results.push(arr1[i])
    i++;
  }
  while (j < arr1.length) {
    results.push(arr2[j])
    j++;
  }
  return results;
}
@lpatmo
Copy link
Member Author

@lpatmo lpatmo commented Mar 2, 2019

Recursive solution:

function mergeSorted(arr1, arr2){
  //base case: arr1 and arr2 are empty, return empty arr
  //if arr1 empty, return arr2
  // if arr2 empty, return arr1
  // otherwise, compare arr1[0] and arr2[0] and return the smallest number + merge(arr1.slice(1), arr2)
  if (arr1.length === 0 && arr2.length === 0) {
    return [];
  } else if (arr1.length === 0 && arr2.length > 0) {
    return arr2;
  } else if (arr2.length === 0 && arr1.length > 0) {
    return arr1;
  } else if (arr1[0] < arr2[0]) {
    return [arr1[0]].concat(merge(arr1.slice(1), arr2))
  } else if (arr1[0] > arr2[0]) {
    return [arr2[0]].concat(merge(arr1, arr2.slice(1)))
  }
}
@ArcTanSusan
Copy link

@ArcTanSusan ArcTanSusan commented Mar 2, 2019

What about the unittests? Adding in unittests is a common requirement in coding exams.

@gauravchl
Copy link
Member

@gauravchl gauravchl commented Mar 2, 2019

One liner es flavored lazy solution

const merge = (arr1=[], arr2=[]) => ([...arr1, ...arr2].sort((a, b)=> a - b))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
3 participants
You can’t perform that action at this time.