Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active December 16, 2019 01:09
Show Gist options
  • Save magnetikonline/f9c5ad7047c23d1f9e531d5f3c9f3077 to your computer and use it in GitHub Desktop.
Save magnetikonline/f9c5ad7047c23d1f9e531d5f3c9f3077 to your computer and use it in GitHub Desktop.
JavaScript implementation of binary insertion sort.
'use strict';
function insertAt(item,sortedList,low = 0,high = (sortedList.length - 1)) {
if (low == high) {
// hit end of sortedList - done
return (item > sortedList[low]) ? low + 1 : low;
}
// get midpoint of list and item value
let mid = low + Math.floor((high - low) / 2),
itemCompare = sortedList[mid];
if (item > itemCompare) {
// work higher end of list
return insertAt(item,sortedList,mid + 1,high);
}
if (item < itemCompare) {
// work lower end of list
return insertAt(item,sortedList,low,mid);
}
// found equal value - done
return mid;
}
// seed list of random ascending (sorted) numbers
let lastValue = 1,
resultIndexList = [lastValue];
for (let i = 1;i < 10000;i++) {
// generate random number at a higher value than last
lastValue = Math.floor(Math.random() * 500) + lastValue;
resultIndexList.push(lastValue);
}
// insert lots of values
let startTime = Date.now();
for (let i = 1;i < 1000;i++) {
// generate random number and insert
let nextValue = Math.floor(Math.random() * 2000000);
resultIndexList.splice(
insertAt(nextValue,resultIndexList),
0,nextValue
);
}
console.log(`Duration: ${(Date.now() - startTime)}ms`);
@QuarkNerd
Copy link

insertAt(4, [1,2,3]) and insertAt(2, [0,1,3]) both return 2, so there is some ambigiuity.

@magnetikonline
Copy link
Author

magnetikonline commented Dec 12, 2019

Hey @QuarkNerd - nicely spotted! Have corrected/fixed!

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