sort

#include <cstdlib>
#include <iostream>
#include <windows.h>
using namespace std;

int comp(const void*a,const void*b) {
    return *(int*)a-*(int*)b;
}

bool good_order(const void *a ,const void *b) {
    return *((long long*)a) < *((long long*)b);
}

template <typename tp>
void my_sort(tp a[],int s,bool good_order(const void* ,const void*)) {
    tp *c=new tp[s],*ic,*ib,*it=a-1,*endb,tem,*endc,*end=a+s;
    int h=1;
    const int csize=sizeof(a);
    while((it+=2)<end) {
        if(good_order(it,(it-1))) {
            tem=*it;
            *it=*(it-1);
            *(it-1)=tem;
        }
    }
    while((h<<=1)<s) {
        endb=a;
        endc=c+h;
        memcpy(c,a,csize);
        while((ib=endb+h)<end) {
            ic=c;
            it=endb;
            if((endb=ib+h)>end) endb=end;
            while(ic!=endc && ib!=endb) {
                if(good_order(ib,ic)) {
                    *it = *ib;
                    ++ib;
                } else {
                    *it = *ic;
                    ++ic;
                }
                ++it;
            }
            while(ic!=endc) *(it++) = *(ic++);
        }
    }
    delete c;
}

template <typename tp>
void my_sort(tp a[],int s,bool good_order(const void* ,const void*),tp c[]) {
    tp *ic,*ib,*it=a-1,*endb,tem,*endc,*end=a+s;
    int h=1;
    const int csize=sizeof(a);
    while((it+=2)<end) {
        if(good_order(it,(it-1))) {
            tem=*it;
            *it=*(it-1);
            *(it-1)=tem;
        }
    }
    while((h<<=1)<s) {
        endb=a;
        endc=c+h;
        memcpy(c,a,csize);
        while((ib=endb+h)<end) {
            ic=c;
            it=endb;
            if((endb=ib+h)>end) endb=end;
            while(ic!=endc && ib!=endb) {
                if(good_order(ib,ic)) {
                    *it = *ib;
                    ++ib;
                } else {
                    *it = *ic;
                    ++ic;
                }
                ++it;
            }
            while(ic!=endc) *(it++) = *(ic++);
        }
    }
}

const int ARRAY_SIZE_=200000;

int main() {
    srand((unsigned)GetTickCount());
    long long *a=new long long[ARRAY_SIZE_],*b=new long long[ARRAY_SIZE_],t;
    int i;
    for(int t=101; --t;) {
        for(i=ARRAY_SIZE_; i;) {
            a[--i]=rand();
            b[i]=rand();
        }
        t=GetTickCount();
        qsort(a,ARRAY_SIZE_,sizeof(long long),comp);
        qsort(b,ARRAY_SIZE_,sizeof(long long),comp);
        t=GetTickCount()-t;
        cout<<t<<endl;

        for(i=ARRAY_SIZE_; i;) {
            a[--i]=rand();
            b[i]=rand();
        }

        t=GetTickCount();
        my_sort(a,ARRAY_SIZE_,good_order,b);
        my_sort(b,ARRAY_SIZE_,good_order,a);
        t=GetTickCount()-t;
        cout<<t<<endl<<endl;
    }
}
相關文章
相關標籤/搜索