Skip to content

Instantly share code, notes, and snippets.

@jviide
Last active March 3, 2020 07:40
Show Gist options
  • Save jviide/cd27218e821007636c77dcde24aaefc8 to your computer and use it in GitHub Desktop.
Save jviide/cd27218e821007636c77dcde24aaefc8 to your computer and use it in GitHub Desktop.
Sorting by __depth with counting sort (O(n) time vs. the usual O(n log n), and sorting is stable)
function sorted(array) {
const maxDepth = array.reduce((acc, cur) => acc > cur.__depth ? acc : cur.__depth, 0);
const offsets = new Array(maxDepth + 1).fill(0);
array.forEach(item => {
offsets[item.__depth]++;
});
let offset = 0;
offsets.forEach((count, index) => {
offsets[index] = offset;
offset += count;
});
const result = new Array(array.length);
array.forEach(item => {
result[offsets[item.__depth]++] = item;
});
return result;
}
array = [
{ text: "give", __depth: 3 },
{ text: "I'm", __depth: 1 },
{ text: "you", __depth: 4 },
{ text: "never", __depth: 1 },
{ text: "up", __depth: 5 },
{ text: "gonna", __depth: 2 }
];
console.log(
sorted(array)
.map(item => item.text)
.join(" ")
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment