Skip to content

Instantly share code, notes, and snippets.

@PaulRBerg
Created December 25, 2022 19:51
Show Gist options
  • Save PaulRBerg/61e5a90434bd4bad31d9dbe9dd0c500e to your computer and use it in GitHub Desktop.
Save PaulRBerg/61e5a90434bd4bad31d9dbe9dd0c500e to your computer and use it in GitHub Desktop.
QuickSort implementation in Solidity v0.8.17
pragma solidity =0.8.17;
function quickSort(uint40[] memory arr, uint40 left, uint40 right) internal pure {
if (left >= right) {
return;
}
unchecked {
// p = the pivot element
uint40 p = arr[(left + right) / 2];
uint40 i = left;
uint40 j = right;
while (i < j) {
while (arr[i] < p) {
++i;
}
while (arr[j] > p) {
--j; // arr[j] > p means p still to the left, so j > 0
}
if (arr[i] > arr[j]) {
(arr[i], arr[j]) = (arr[j], arr[i]);
} else {
++i;
}
}
// Note --j was only done when a[j] > p. So we know: a[j] == p, a[<j] <= p, a[>j] > p
if (j > left) {
quickSort(arr, left, j - 1); // j > left, so j > 0
}
quickSort(arr, j + 1, right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment