From d6602b92fba4f15a58f9077125ee8be13a82b154 Mon Sep 17 00:00:00 2001 From: Anna Matveev Date: Thu, 25 Jan 2018 14:39:00 +0200 Subject: [PATCH] Update sortedMerge.js --- chapter10/10.01 - Sorted Merge/sortedMerge.js | 67 ++++--------------- 1 file changed, 12 insertions(+), 55 deletions(-) diff --git a/chapter10/10.01 - Sorted Merge/sortedMerge.js b/chapter10/10.01 - Sorted Merge/sortedMerge.js index ce04435..55c6579 100644 --- a/chapter10/10.01 - Sorted Merge/sortedMerge.js +++ b/chapter10/10.01 - Sorted Merge/sortedMerge.js @@ -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]); + p1++; + p2++; + } } + a = a.concat(b.slice(p2)); return a; } };