Skip to content

Instantly share code, notes, and snippets.

@westc
Created October 10, 2023 15:56
Show Gist options
  • Save westc/48f5eda5f098765dca53e44d202b4f06 to your computer and use it in GitHub Desktop.
Save westc/48f5eda5f098765dca53e44d202b4f06 to your computer and use it in GitHub Desktop.
A quick implementation of quick sort.
/**
* A quick implementation of quick sort.
* @template T
* @param {T[]} values
* The values to sort.
* @returns {T[]}
* The sorted array of values.
*/
function quickSort(values) {
const segments = [{start: 0, end: values.length - 1}];
for (let segment; segment = segments.shift();) {
let {start, end} = segment;
if (start < end) {
let moveToIndex = start;
let value = values[end];
for (let index = start, lastIndex = end - 1; index <= lastIndex; index++) {
if (values[index] <= value) {
if (index > start) {
[values[moveToIndex], values[index]] = [values[index], values[moveToIndex]];
}
moveToIndex++;
}
}
if (moveToIndex < end) {
values.splice(moveToIndex, 0, values.splice(end, 1)[0]);
}
segments.push({start, end: moveToIndex - 1});
segments.push({start: moveToIndex + 1, end});
}
}
return values;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment