Last active
August 29, 2015 14:01
-
-
Save jprupp/28e1d2868848a46b9760 to your computer and use it in GitHub Desktop.
Recursive QuickSort in C++ (memory-efficient)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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