/***********************************************************
 * A Comparison between BEAD SORT, DISTRIBUTION COUNTING
 * and MERGE SORT.
 * by Dominik Schultes
 * 25. March 2004
 ***********************************************************/

#include <sys/time.h>
#include <iostream>
#include <fstream>
#include <vector>


using namespace std;

typedef vector<int> my_vector;


/***********************************************************
 * This section contains methods to measure the used time
 * and to log the measured values.
 ***********************************************************/
bool log_n = true;
double last_timestamp;

/** Returns a current timestamp. */
inline double timestamp()
{
    struct timeval tp;
    gettimeofday (&tp, NULL);
    return double (tp.tv_sec) + tp.tv_usec / 1000000.;
}

/** Starts the time measurement. */
inline void start_timer() {
    last_timestamp = timestamp();
}

/** Stops the time measurement and returns the elapsed time. */
inline double stop_timer() {
    return timestamp() - last_timestamp;
}

/**
   Writes the given time to the given output stream.
   Depending on the global variable log_n either n or m
   is used as variable that the given time is assigned to.
*/
inline void logTime(int m, int n, double t, ostream &out) {
    if (log_n) out << n; else out << m;
    out << " " << t << endl;
}


/***********************************************************
 * This section contains methods to generate the input
 * randomly and to check the output if it is really sorted
 ***********************************************************/

/**
   Generates n random numbers between 1 and m and inserts them
   to the given vector a.
*/
void generateData(my_vector &a, int n, int m) {
    for (int i=0; i<n; i++) {
	a.push_back( (int)(rand() / (double)(RAND_MAX+1.0) * m)+1 );
    }
}

/**
   Checks if the given vector a is sorted in descending order.
   Writes a message to standard out.
*/
void checkData(my_vector &a) {
    for (int i=1; i<a.size(); i++) {
	if (a[i] > a[i-1]) {
	    cout << "Check FAILED !" << endl << (i-1) << ": "
		 << a[i-1] << endl << i << ": " << a[i] << endl;
	    return;
	}
    }
    cout << "Check passed. Data is sorted." << endl;
}


/***********************************************************
 * This section contains the actual sorting methods:
 * Bead Sort, Distribution Counting and Merge Sort
 ***********************************************************/

/** A simple implementation of Bead Sort. */
void beadSort(my_vector &a, int m, ostream &out) {
    // initialize
    int n = a.size();
    
    int *level_count = new int[n+1];
    int *rod_count = new int[m+1];

    for (int i=1; i<=n; i++) level_count[i] = 0;
    for (int i=1; i<=m; i++) rod_count[i] = 0;

    // sort
    start_timer();
    
    for (int i=0; i<n; i++) {	
	for (int j=1; j<=a[i]; j++) {
	    ++level_count[ ++rod_count[j] ];
	}
    }
    
    logTime( m, n, stop_timer(), out );
    
    // write sorted data back and clean up
    a.clear();
    for (int i=1; i<=n; i++) a.push_back( level_count[i] );
    
    delete level_count;
    delete rod_count;
}

/** A simple implementation of Distribution Counting. */
void distributionCounting(my_vector &a, int m, ostream &out) {
    // initialize
    int n = a.size();

    int *result = new int[n];
    int *buckets = new int[m+1];
    for (int i=1; i<=m; i++) buckets[i] = 0;

    // sort
    start_timer();
    
    for (int i=0; i<n; i++) buckets[a[i]]++;

    for (int i=m-1; i>=1; i--) buckets[i] += buckets[i+1];
    
    for (int i=0; i<n; i++) result[ --buckets[a[i]] ] = a[i];
    
    logTime( m, n, stop_timer(), out );

    // write sorted data back and clean up
    a.clear();
    for (int i=0; i<n; i++) a.push_back( result[i] );

    delete result;
    delete buckets;
}

/** A recursive implementation of Merge Sort. */
void mergeSortRecursion(my_vector &a, int l, int r) {
    // base cases
    if (l == r) return;
    if (r - l == 1) {
	if (a[r] > a[l]) {
	    int tmp = a[l]; a[l] = a[r]; a[r] = tmp;
	}
	return;
    }

    // recursive calls
    int m = (r-l)/2 + l;
    mergeSortRecursion(a,l,m);
    mergeSortRecursion(a,m+1,r);

    // merge
    my_vector b;
    b.reserve(r-l+1);
    int j = l; int k = m+1;
    for (int i=l; i<=r; i++) {
	if ((j > m) || ((k <= r) && (a[j] < a[k])))
	    b.push_back(a[k++]);
	else
	    b.push_back(a[j++]);
    }
    
    // write sorted data back
    j = 0;
    for (int i=l; i<=r; i++) a[i] = b[j++];
}

/**
   Invokes the recursive Merge Sort with the appropriate
   arguments.
*/
void mergeSort(my_vector &a, int m, ostream &out) {
    start_timer();
    mergeSortRecursion(a, 0, a.size()-1);
    logTime( m, a.size(), stop_timer(), out );
}


/***********************************************************
 * This section contains the main method and methods that
 * control the test runs.
 ***********************************************************/

/**
   Performs several test runs. The number of keys n varies between
   500 000 and 10 000 000 with a step size of 500 000. No key is
   bigger than a fixed m = 100.
*/
void measurement1() {
    ofstream outFileDistrCount( "distrCount1.dat" );
    ofstream outFileBead( "beadSort1.dat" );
    ofstream outFileMerge( "mergeSort1.dat" );

    int m = 100;
    log_n = true;
    int step = 500000;

    for (int n=step; n<=20*step; n+=step) {
	cout << n << endl;

	// generate the data
	my_vector *data1 = new my_vector;
	generateData(*data1, n, m);    
	my_vector *data2 = new my_vector(*data1);
	my_vector *data3 = new my_vector(*data1);

	// sort
	distributionCounting(*data1,m,outFileDistrCount);
    	beadSort(*data2,m,outFileBead);
	mergeSort(*data3,m,outFileMerge);

	// check the results and clean up
	assert(*data1 == *data2);
	assert(*data1 == *data3);

	checkData(*data1);
	checkData(*data2);
	checkData(*data3);

	delete data1;
	delete data2;
	delete data3;
    }
}

/**
   Performs several test runs. The number of keys n is fixed
   to 5 000 000. The maximum key m varies between 10 and 1000
   with a step size of 10.
*/
void measurement2() {
    ofstream outFileDistrCount( "distrCount2.dat" );
    ofstream outFileBead( "beadSort2.dat" );
    ofstream outFileMerge( "mergeSort2.dat" );
    
    int n = 5000000;
    log_n = false;

    for (int m=10; m<=1000; m+=10) {
	cout << m << endl;

	// generate the data
	my_vector *data1 = new my_vector;
	generateData(*data1, n, m);    
	my_vector *data2 = new my_vector(*data1);
	my_vector *data3 = new my_vector(*data1);

	// sort
	distributionCounting(*data1,m,outFileDistrCount);
    	beadSort(*data2,m,outFileBead);
	mergeSort(*data3,m,outFileMerge);

	// check the results and clean up
	assert(*data1 == *data2);
	assert(*data1 == *data3);

	checkData(*data1);
	checkData(*data2);
	checkData(*data3);

	delete data1;
	delete data2;
	delete data3;
    }
}

/** The main method. */
int main() {

    measurement1();
    measurement2();
    
    return 0;
}
