Skip to content

Instantly share code, notes, and snippets.

@Broxzier
Created October 10, 2024 20:40
Show Gist options
  • Save Broxzier/f68d7a5f580aace01b92966f8e7871ab to your computer and use it in GitHub Desktop.
Save Broxzier/f68d7a5f580aace01b92966f8e7871ab to your computer and use it in GitHub Desktop.
This is an implementation of the quick sort algorithm, written from memory as an excersice.
#include <utility> // For std::swap
template <typename T>
void quick_sort(T array[], size_t size)
{
constexpr auto npos = (size_t{ 0 } - 1);
// Empty or doesn't need sorting
if (size <= 1)
return;
// Select the last element as pivot
auto pivotIndex = size - 1;
auto& pivotValue = array[pivotIndex];
auto leftIterator = size_t{ 0 };
auto rightIterator = pivotIndex - 1;
while (rightIterator != npos && rightIterator >= leftIterator)
{
// increase the left iterator until we find a value that is higher than the pivot value or it crosses bounds
while (leftIterator < pivotIndex && array[leftIterator] <= pivotValue)
leftIterator++;
// decrease the right iterator until we find a value that is lower than the pivot value or it crosses bounds
while (rightIterator != npos && rightIterator >= leftIterator && array[rightIterator] > pivotValue)
rightIterator--;
if (rightIterator != npos && rightIterator >= leftIterator)
std::swap(array[leftIterator], array[rightIterator]);
}
// The pivot value should be on the left iterator's position
std::swap(array[leftIterator], array[pivotIndex]);
// Recursively sort each side of the pivot point. Everything on the left side is lower and everything on the right side is higher than it
quick_sort(array, leftIterator);
quick_sort(array + leftIterator + 1, size - leftIterator - 1);
}
// Allow calling quick_sort on a static array
template<typename T, size_t N>
void quick_sort(T(&array)[N])
{
quick_sort(array, N);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment