Cod sursa(job #689999)

Utilizator AndreyPAndrei Poenaru AndreyP Data 25 februarie 2012 00:57:24
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.16 kb
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <algorithm>
using namespace std;

template< typename T >
class QuickSorter {

private:
    int n;
    T *v;
    bool (*compar) (const T&, const T&);

    inline int part(int p,int u) {
        int piv = p + (rand() % (u - p));
        int i = p, j = u - 1;

        while (i < j) {
            while (compar(v[i], v[piv])) {
                ++i;
            }

            while(compar(v[piv], v[j])) {
                --j;
            }

            if (i < j) {
                swap(v[i], v[j]);

                if (i == piv) {
                    piv = j;
                } else
                if (j == piv) {
                    piv = i;
                }

                ++i;
                --j;
            }
        }

        // i == j
        // Ma asigur si ca nu ramane nicio "jumatate" goala
        if (compar(v[i], v[piv])) {
            if (i == u - 1) {
                swap(v[i], v[piv]);
            } else {
                ++i;
            }
        } else
        if (i == p) {
            swap(v[i], v[piv]);
            ++i;
        }

        return i;
    }

    void quickSort(int p, int u) {
        if (u - p < 2) {
            return;
        }

        int r = part(p, u);

        quickSort(p, r);
        quickSort(r, u);
    }

public:
    QuickSorter(int n, T *v, bool (*compar) (const T&, const T&)) {
        this -> n = n;
        this -> v = v;
        this -> compar = compar;

        srand(time(NULL));
    }

    void sort() {
        quickSort(0, n);
    }
};

inline void read(int &n, int *&v) {
    ifstream fin("algsort.in");

    fin >> n;
    v = new int[n];

    for (int i = 0; i < n; ++i) {
        fin >> v[i];
    }

    fin.close();
}

bool compar(const int &x, const int &y) {
    return (x < y);
}

inline void print(const int n, const int * const v) {
    ofstream fout("algsort.out");

    fout << v[0];
    for (int i = 1; i < n; ++i) {
        fout << " " << v[i];
    }

    fout << "\n";
    fout.close();
}

int main() {
    int n, *v;

    read(n, v);

    QuickSorter< int > quickSorter(n, v, compar);
    quickSorter.sort();

    print(n, v);
    delete[] v;

    return 0;
}