Skip to content

Instantly share code, notes, and snippets.

@Izhaki
Last active August 22, 2018 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Izhaki/834a9d37d1ad34c6179b6a16e670b526 to your computer and use it in GitHub Desktop.
Save Izhaki/834a9d37d1ad34c6179b6a16e670b526 to your computer and use it in GitHub Desktop.
// Finds the insertion index for an item in an array.
// Uses compareFn (similar to that provided to array.sort())
const getInsertionIndex = (arr, item, compareFn) => {
const itemsCount = arr.length;
// No items in array, so return insertion index 0
if (itemsCount === 0) {
return 0;
}
const lastItem = arr[itemsCount - 1];
// In case the item is beyond the end of this array, or
// identical to the last item.
// We need this as for arrays with 1 item start and end will be
// 0 so we never enter the while loop below.
if (compareFn(item, lastItem) >= 0) {
return itemsCount;
}
const getMidPoint = (start, end) => Math.floor((end - start) / 2) + start;
let start = 0;
let end = itemsCount - 1;
let index = getMidPoint(start, end);;
// Binary search - start in middle, divide and conquer.
while (start < end) {
const curItem = arr[index];
const comparison = compareFn(item, curItem);
if (comparison === 0) {
// Indentical item
break;
} else if (comparison < 0) {
// Target is lower in array, move the index halfway down.
end = index;
} else {
// Target is higher in array, move the index halfway up.
start = index + 1;
}
index = getMidPoint(start, end);
}
return index;
};
@Izhaki
Copy link
Author

Izhaki commented Aug 22, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment