Created
December 5, 2017 13:57
-
-
Save PantherHawk/f16c0ac914ab94f3cdddf471c6b1e90b to your computer and use it in GitHub Desktop.
Median of two sorted arrays implementation. For Leet Code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var findMedianSortedArrays = function(nums1, nums2) { | |
// new tactic, merge sort the two arrays, and then find the median. | |
let sorted = mergeSort(nums1.concat(nums2)); | |
if (sorted.length % 2 === 0) { | |
return handleEven(sorted); | |
} | |
return handleOdd(sorted); | |
} | |
function mergeSort(arr) { | |
// cut array down to singletons | |
if (arr.length < 2) | |
return arr; | |
// break down the middle | |
var middle = parseInt(arr.length / 2); | |
// slice the left | |
var left = arr.slice(0, middle); | |
// slice the right | |
var right = arr.slice(middle, arr.length); | |
// throw into the call stack of merge what your cutting up | |
return merge(mergeSort(left), mergeSort(right)); | |
} | |
function merge(left, right) { | |
// keep the results | |
var result = []; | |
// as long as both left and right slices contain elements, compare | |
while (left.length && right.length) { | |
if (left[0] <= right[0]) { | |
// add to the results the smaller element | |
result.push(left.shift()); | |
} else { | |
result.push(right.shift()); | |
} | |
} | |
// add to the results the leftovers of the longer array | |
while (left.length) | |
result.push(left.shift()); | |
while (right.length) | |
result.push(right.shift()); | |
return result; | |
} | |
function handleOdd(array) { | |
// find the middle number | |
return array[Math.floor(array.length / 2)]; | |
} | |
function handleEven(array) { | |
return (array[Math.floor(array.length /2)] + array[Math.floor(array.length /2) - 1]) / 2; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment