Skip to content

Instantly share code, notes, and snippets.

@Ratstail91
Created September 27, 2014 06:50
Show Gist options
  • Save Ratstail91/f55776033899a763df1c to your computer and use it in GitHub Desktop.
Save Ratstail91/f55776033899a763df1c to your computer and use it in GitHub Desktop.
Stack-based, inplace, recursive quicksort. I'm quite proud of this, I think it's quite clever. Odd numbers are sorted to the front, BTW.
int CompareOddEven(int lhs, int rhs)
{
//lhs < rhs ? -1, 1, 0
//odd vs even
if (lhs % 2 == 1 && rhs % 2 == 0) {
return -1;
}
if (lhs % 2 == 0 && rhs % 2 == 1) {
return 1;
}
//size
if (lhs < rhs) {
return -1;
}
if (lhs > rhs) {
return 1;
}
return 0;
}
inline void SwapReferences(int& lhs, int& rhs)
{
//importantly, swapping the same value doesn't cause issues like XOR
int tmp = lhs;
lhs = rhs;
rhs = tmp;
}
void SortOddEven(int* numbers, int count)
{
//error checking
if (!numbers || count < 2) {
return;
}
//stack-based, inplace, recursive quicksort FTW
int pivot = count / 2;
int stack = pivot;
int iter = pivot;
//left of the pivot
while (--iter >= 0) {
if (CompareOddEven(numbers[iter], numbers[pivot]) > 0) {
//push to the stack
SwapReferences(numbers[iter], numbers[--stack]);
}
}
//move the stack
SwapReferences(numbers[stack], numbers[pivot]);
SwapReferences(stack, pivot);
//reset, skipping the pre-existing stack in the next loop
iter = stack;
stack = pivot;
//right of the pivot
while(++iter < count) {
if (CompareOddEven(numbers[iter], numbers[pivot]) < 0) {
//push to the stack
SwapReferences(numbers[iter], numbers[++stack]);
}
}
//move the stack
SwapReferences(numbers[stack], numbers[pivot]);
SwapReferences(stack, pivot);
//recursive calls
SortOddEven(numbers, pivot);
SortOddEven(numbers + pivot + 1, count - pivot - 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment