Cod sursa(job #1389030)

Utilizator andreiiiiPopa Andrei andreiiii Data 15 martie 2015 21:30:33
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.36 kb
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;

int A[100005];

#define INSERTION_LIMIT 7

template<class iterator, class comparator>
void downheap(iterator begin, int N, int pos, comparator cmp) {
    pos++;
    while (2 * pos <= N) {
        int son = 2 * pos;
        if (son + 1 <= N && cmp(*(begin + son - 1), *(begin + son)))
            ++son;
        if (cmp(*(begin + pos - 1), *(begin + son - 1))) {
            swap(*(begin + pos - 1), *(begin + son - 1));
            pos = son;
        } else {
            break;
        }
    }
}

template<class iterator, class comparator>
void heapsort(iterator begin, iterator end, comparator cmp) {
    int N = end - begin;
    for (int i = N / 2 - 1; i >= 0; --i)
        downheap(begin, N, i, cmp);
    for (int i = N - 1; i > 0; --i) {
        swap(*begin, *(begin + i));
        downheap(begin, i, 0, cmp);
    }
}

template<class iterator, class comparator>
void sort(iterator begin, iterator end, comparator cmp, size_t depth, size_t limit) {
    if (begin >= end) return;
    if (end - begin <= INSERTION_LIMIT) {
        for (iterator i = begin; i != end; ++i) {
            iterator j = i;
            while (j != begin && cmp(*j, *(j - 1))) {
                swap(*j, *(j - 1));
                j--;
            }
        }
    }
    if (depth == limit) heapsort(begin, end, cmp);
    else {
        typedef typename iterator_traits<iterator>::value_type type;
        type pivot = *(begin + (end - begin) / 2);

        iterator i = begin, j = end - 1;
        while (i <= j) {
            while (cmp(*i, pivot) && i < end - 1) ++i;
            while (cmp(pivot, *j) && j > begin) --j;
            if (i <= j) {
                swap(*i, *j);
                ++i;
                --j;
            }
        }
        sort(i, end, cmp, depth + 1, limit);
        sort(begin, j + 1, cmp, depth + 1, limit);
    }
}

template<class iterator, class comparator>
void sort(iterator begin, iterator end, comparator cmp) {
    size_t limit;
    for (limit = 1; (1 << limit) < end - begin; ++limit);
    sort(begin, end, cmp, 0, 2 * limit);
}

int main() {
    ifstream fin("algsort.in");
    ofstream fout("algsort.out");

    int N;
    fin >> N;
    for (int i = 0; i < N; ++i)
        fin >> A[i];

    sort(A, A + N, less<int>());

    for (int i = 0; i < N; ++i)
        fout << A[i] << ' ';

    fin.close();
    fout.close();
}