Skip to content

Instantly share code, notes, and snippets.

@jprupp
Last active August 29, 2015 14:01
Show Gist options
  • Save jprupp/28e1d2868848a46b9760 to your computer and use it in GitHub Desktop.
Save jprupp/28e1d2868848a46b9760 to your computer and use it in GitHub Desktop.
Recursive QuickSort in C++ (memory-efficient)
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
void qs(int count, int ls[])
{
int pivot, *hole;
if (count < 1) return;
pivot = ls[count / 2];
hole = ls + count / 2;
for (int i = count / 2 + 1; i < count; i++)
{
if (ls[i] < pivot)
{
*hole = ls[i];
ls[i] = *(hole + 1);
hole = hole + 1;
}
}
for (int i = 0; i < count / 2; i++)
{
if (ls[i] >= pivot)
{
*hole = ls[i];
ls[i] = *(hole - 1);
hole = hole - 1;
}
}
*hole = pivot;
// Recurse into list of numbers smaller than pivot.
qs(hole - ls, ls);
// Recurse into list of numbers greater or equal than pivot.
qs(ls + count - hole - 1, hole + 1);
}
int main()
{
int count = pow(2, 30);
int *ls;
ls = (int*) malloc(sizeof(int) * count);
for (int j = count, k = 0; j > 0; j--, k++)
{
ls[k] = j;
}
cout << "List created." << endl;
qs(count, ls);
cout << "First seven: " << ls[0];
for (int i = 1; i < 7; i++) cout << ", " << ls[i];
cout << endl;
cout << "Last seven: " << ls[count - 7];
for (int i = count - 6; i < count; i++) cout << ", " << ls[i];
cout << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment