Skip to content

Commit

Permalink
optimize tail calls in feature state sorting (#9463)
Browse files Browse the repository at this point in the history
  • Loading branch information
mourner authored Apr 1, 2020
1 parent 2faf0ab commit 928f3dd
Showing 1 changed file with 23 additions and 17 deletions.
40 changes: 23 additions & 17 deletions src/data/feature_position_map.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,25 +95,31 @@ function getNumericId(value: mixed) {
}

// custom quicksort that sorts ids, indices and offsets together (by ids)
// uses Hoare partitioning & manual tail call optimization to avoid worst case scenarios
function sort(ids, positions, left, right) {
if (left >= right) return;

const pivot = ids[(left + right) >> 1];
let i = left - 1;
let j = right + 1;

while (true) {
do i++; while (ids[i] < pivot);
do j--; while (ids[j] > pivot);
if (i >= j) break;
swap(ids, i, j);
swap(positions, 3 * i, 3 * j);
swap(positions, 3 * i + 1, 3 * j + 1);
swap(positions, 3 * i + 2, 3 * j + 2);
}
while (left < right) {
const pivot = ids[(left + right) >> 1];
let i = left - 1;
let j = right + 1;

while (true) {
do i++; while (ids[i] < pivot);
do j--; while (ids[j] > pivot);
if (i >= j) break;
swap(ids, i, j);
swap(positions, 3 * i, 3 * j);
swap(positions, 3 * i + 1, 3 * j + 1);
swap(positions, 3 * i + 2, 3 * j + 2);
}

sort(ids, positions, left, j);
sort(ids, positions, j + 1, right);
if (j - left < right - j) {
sort(ids, positions, left, j);
left = j + 1;
} else {
sort(ids, positions, j + 1, right);
right = j;
}
}
}

function swap(arr, i, j) {
Expand Down

0 comments on commit 928f3dd

Please sign in to comment.