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

Update sortedMerge.js #28

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 12 additions & 55 deletions chapter10/10.01 - Sorted Merge/sortedMerge.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,63 +2,20 @@ const sortedMerge = (a, b) => {
if (a === undefined || b === undefined) {
return 'where are your arrays?';
} else {
// naive solution: create new array and merge
// create new array
let answer = [];
// declare pointers for A and B
let pointerA = 0;
let pointerB = 0;
// use pointers to iterate through A and B and insert elements into new array
/*
while (pointerA < a.length || pointerB < b.length) {
if (pointerA === a.length) {
answer.push(b[pointerB]);
pointerB++;
} else if (pointerB === b.length) {
answer.push(a[pointerA]);
pointerA++;
} else if (a[pointerA] < b[pointerB]) {
answer.push(a[pointerA]);
pointerA++;
} else {
answer.push(b[pointerB]);
pointerB++;
}
}
return answer;
*/

// in-place solution: merge into A in place
// helper function: move back array one space, from pointer to end
const moveBack = (arr, pt, end) => {
let currPt = end;
while (currPt > pt) {
arr[currPt] = arr[currPt - 1];
currPt--;
}
};
let p1 = 0;
let p2 = 0;

let end = a.length;
// while pointerB is still traversing through B
while (pointerB < b.length) {
// if pointerA is done traversing (should just append all of B to back of A)
if (pointerA === end) {
a[pointerA] = b[pointerB];
pointerA++;
pointerB++;
end++;
// else if value at pointerA is smaller that value at pointerB (should not insert, continue traversing A)
} else if (a[pointerA] < b[pointerB]) {
pointerA++;
} else {
// otherwise move all elements from pointerA back by one space, and insert value at pointerB into a
moveBack(a, pointerA, end);
a[pointerA] = b[pointerB];
pointerA++;
pointerB++;
end++;
}
while (p1< a.length && p2 < b.length) {
if (a[p1] < b[p2]) {
p1++;
}
else {
a.splice(p1,0,b[p2]);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These slices might/will actually be expensive for large inputs; think about it.

p1++;
p2++;
}
}
a = a.concat(b.slice(p2));
return a;
}
};
Expand Down