Skip to content

Instantly share code, notes, and snippets.

@hartz89
Last active June 21, 2019 20:36
Show Gist options
  • Save hartz89/adf121911694b0af22d4c7ed34ad9f64 to your computer and use it in GitHub Desktop.
Save hartz89/adf121911694b0af22d4c7ed34ad9f64 to your computer and use it in GitHub Desktop.
Implementation of a binary insertion sort in es6.
export const getInsertPosition = (value, target) => {
if (target.length === 0) {
return 0;
}
if (value < target[0]) {
return 0;
}
const lastIndex = target.length - 1;
if (value > target[lastIndex]) {
return target.length;
}
const index = Math.floor(lastIndex / 2);
const valueAtIndex = target[index];
if (value === valueAtIndex) {
return index;
}
if (value > valueAtIndex) {
return index + getInsertPosition(value, target.slice(index + 1)) + 1;
}
if (value < valueAtIndex) {
return getInsertPosition(value, target.slice(0, index));
}
};
export const insertInOrder = (value, target) => {
const insertPosition = getInsertPosition(value, target);
return target.splice(insertPosition, 0, value);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment