Skip to content

Instantly share code, notes, and snippets.

@KEIII
Created October 13, 2021 19:11
Show Gist options
  • Save KEIII/43c1fe5e305b20a20087bcf051c12117 to your computer and use it in GitHub Desktop.
Save KEIII/43c1fe5e305b20a20087bcf051c12117 to your computer and use it in GitHub Desktop.
Quicksort
const swap = (items, first, second) => {
const tmp = items[first];
items[first] = items[second];
items[second] = tmp;
};
const partition = (items, left, right) => {
const pivot = items[Math.trunc((right + left) / 2)];
while (left <= right) {
while (items[left] < pivot) left++;
while (items[right] > pivot) right--;
if (left <= right) {
swap(items, left, right);
left++;
right--;
}
}
return left;
};
export const qsort = (items) => {
if (items.length < 2) return;
const go = (items, left, right) => {
if (left >= right) return;
const mid = partition(items, left, right);
go(items, left, mid - 1);
go(items, mid, right);
};
go(items, 0, items.length - 1);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment