Skip to content

Instantly share code, notes, and snippets.

@thomasvaeth
Created February 19, 2018 18:32
Show Gist options
  • Save thomasvaeth/443726625b92df9b79c6305f24446dfb to your computer and use it in GitHub Desktop.
Save thomasvaeth/443726625b92df9b79c6305f24446dfb to your computer and use it in GitHub Desktop.
"The further a society drifts from the truth, the more it will hate those that speak it." - George Orwell
function minimumDiff(arr) {
var sortedArr = mergeSort(arr),
difference = sortedArr[1] - sortedArr[0];
for (var i = 1; i < sortedArr.length; i++) {
if (sortedArr[i] - sortedArr[i - 1] < difference) {
difference = sortedArr[i] - sortedArr[i - 1];
}
}
return difference;
}
function mergeSort(arr) {
if (arr.length < 2) return arr;
var middle = Math.floor(arr.length / 2),
left = arr.slice(0, middle),
right = arr.slice(middle);
return merge(
mergeSort(left),
mergeSort(right)
);
}
function merge(left, right) {
var result = [],
indexLeft = 0,
indexRight = 0;
while (indexLeft < left.length && indexRight < right.length) {
if (left[indexLeft] < right[indexRight]) {
result.push(left[indexLeft]);
indexLeft++;
} else {
result.push(right[indexRight]);
indexRight++;
}
}
return result.concat(left.slice(indexLeft)).concat(right.slice(indexRight));
}
minimumDiff([130, 5, 20, 9]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment