Last active
June 21, 2019 20:36
-
-
Save hartz89/adf121911694b0af22d4c7ed34ad9f64 to your computer and use it in GitHub Desktop.
Implementation of a binary insertion sort in es6.
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
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