Skip to content

Instantly share code, notes, and snippets.

@bitnenfer
Created January 29, 2024 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitnenfer/6cd6d3f4204155f44a32738e01424304 to your computer and use it in GitHub Desktop.
Save bitnenfer/6cd6d3f4204155f44a32738e01424304 to your computer and use it in GitHub Desktop.
Quicksort in C++
#include <vector>
#include <stack>
int partition(std::vector<int>& input, int left, int right)
{
if (left < right)
{
int pivotValue = input[right];
// This represent the current position of the pivot
int pivotIndex = left;
for (int index = pivotIndex; index < right; ++index)
{
if (input[index] <= pivotValue)
{
// We swap the current value with the one in the pivot position
// increment the pivot index
std::swap(input[index], input[pivotIndex++]);
}
}
// Finally swap the pivot value which is at the right of the array with the value in the pivot index.
// Which should be >= to the pivot value
std::swap(input[pivotIndex], input[right]);
return pivotIndex;
}
return -1;
}
void quickSortRec(std::vector<int>& input, int l, int r)
{
if (l < r)
{
int j = partition(input, l, r);
quickSortRec(input, l, j - 1);
quickSortRec(input, j + 1, r);
}
}
#define USE_RECURSIVE 0
void quickSort(std::vector<int>& input)
{
#if USE_RECURSIVE
quickSortRec(input, 0, input.size() - 1);
#else
// we just use a stack for the iterative version.
// this will just simulate the stack of recursion.
std::stack<int> stack;
stack.push(0);
stack.push(input.size() - 1);
while (!stack.empty())
{
int right = stack.top();
stack.pop();
int left = stack.top();
stack.pop();
if (left < right)
{
int pivotIndex = partition(input, left, right);
if (left < pivotIndex - 1)
{
stack.push(left);
stack.push(pivotIndex - 1);
}
if (right > pivotIndex + 1)
{
stack.push(pivotIndex + 1);
stack.push(right);
}
}
}
#endif
}
int main()
{
std::vector<int> test1 = { 6, 3, 7, 5, 1, 2 };
std::vector<int> test2 = { 33, 34, 212, -321, 4, 4 ,2, 1 };
std::vector<int> test3 = { 9, 2, 1, 4893, 2, 43, -1 };
quickSort(test1);
quickSort(test2);
quickSort(test3);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment