Skip to content

Instantly share code, notes, and snippets.

@grodtron
Created July 19, 2012 02:43
Show Gist options
  • Save grodtron/3140418 to your computer and use it in GitHub Desktop.
Save grodtron/3140418 to your computer and use it in GitHub Desktop.
An implementation of quicksort (Not completely working)
#include <iostream>
using std::cout;
using std::endl;
//#define DEBUG 1
#include <stdlib.h>
#include <time.h>
void _qsort(int *, int);
int main()
{
#ifdef DEBUG
const int size = 1 << 5;
#else
const int size = 1 << 20;
#endif
srand(time(0));
int * array = new int[size];
for(int i = 0; i < size; ++i){
array[i] = rand() % (size/2);
}
cout << "sorting... ";
cout.flush();
_qsort(array, size);
cout << "done!" << endl;
cout << "Checking sortedness... ";
cout.flush();
bool sorted = true;
for(int i = 1; i < size; ++i){
sorted = sorted && (array[i-1] <= array[i]);
}
cout << "done!" << endl;
cout << (sorted ? "SUCCESS!" : "FAILURE!") << endl;
return 0;
}
void swap(int * a, int * b){
int c = *a;
*a = *b;
*b = c;
}
void _qsort(int * array, int length){
int * R = array + length - 1;
int * L = array;
int Ldist = 1;
int Rdist = 1;
int Rlen = 0;
int Llen = 0;
int pivot = *(array + (length/2));
if (length < 2) return;
while(1){
while(*R >= pivot){
if(*R > pivot){
--R;
++Rlen;
}else{
while(*(R - Rdist) == pivot && (R - Rdist) > L){
++Rdist;
}
if((R - Rdist) > L){
swap(R, R - Rdist);
}else{
break;
}
}
}
while(*L <= pivot){
if(*L < pivot){
++L;
++Llen;
}else{
while(*(L + Ldist) == pivot && (L + Ldist) < R){
++Ldist;
}
if((L + Ldist) < R){
swap(L, L + Ldist);
}else{
break;
}
}
}
if(*L > pivot || *R < pivot){
swap(L, R);
}else{
break;
}
}
#ifdef DEBUG
cout << "List of length " << length << " split into:" << endl
<< " left: " << Llen << endl
<< " pivot: " << ((int)(R - L) + 1) << endl
<< " right: " << Rlen << endl;
cout << "With pivot: " << pivot << endl;
cout << " total list:" << endl << " ";
for(int i = 0; i < length; ++i){
cout << array[i] << ' ';
if(array + i + 1 == L || array + i == R){
cout << "| ";
}
}
cout << endl;
cout << " left list:" << endl << " ";
for(int i = 0; i < Llen; ++i){
cout << array[i] << ' ';
}
cout << endl;
cout << " right list:" << endl << " ";
for(int i = 0; i < Rlen; ++i){
cout << (array + length - Rlen)[i] << ' ';
}
cout << endl;
#endif
_qsort(array, Llen);
_qsort(array + length - Rlen, Rlen);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment