Created
October 10, 2023 15:56
-
-
Save westc/48f5eda5f098765dca53e44d202b4f06 to your computer and use it in GitHub Desktop.
A quick implementation of quick sort.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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