行云

行至水穷处,坐看云起时。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

用于测试排序算法的正确性和性能
测试函数:

View Code
/*
    分别测试
    记录有序、反序、随机、所有元素相同的情况
*/
typedef void (*SortFun)(int *, int *);
SortFun pFun;


void OrderTest( int n)
{
    clock_t start;
    float time_used;
    int *p = new int[n];

    pFun = HeapSort;
    //ascending order
    int i=0;
    int flg;
    while (i<n)
        p[i] = i++;
    start = clock();
    pFun(p, p+n);
    time_used = (float)(clock() - start)/CLOCKS_PER_SEC;
    flg = IsSorted(p, p+n);
    printf("Ascending order: %s \n", flg?"OK":"Not OK");
    printf("time: %f\n", time_used);

    //descending order
    i=0;
    while (i<n)
    {
        p[i] = n-i;
        i++;
    }
    start = clock();
    pFun(p, p+n);
    time_used = (float)(clock() - start)/CLOCKS_PER_SEC;
    flg = IsSorted(p, p+n);
    printf("Descending order: %s \n", flg?"OK":"Not OK");
    printf("time: %f\n", time_used);

    //random order
    i=0;
    while (i<n)
        p[i++] = rand();
    start = clock();
    pFun(p, p+n);
    time_used = (float)(clock() - start)/CLOCKS_PER_SEC;
    flg = IsSorted(p, p+n);
    printf("Random order: %s \n", flg?"OK":"Not OK");
    printf("time: %f\n", time_used);

    //Same value with all elements
    i = 0;
    while (i<n)
        p[i++] = 6;
    start = clock();
    pFun(p, p+n);
    time_used = (float)(clock() - start)/CLOCKS_PER_SEC;
    flg = IsSorted(p, p+n);
    printf("All same: %s \n", flg?"OK":"Not OK");
    printf("time: %f\n\n", time_used);

    delete [] p;
}


void PerformanceTest( int n)
{
    printf("** Performance **\n");
    clock_t start;
    float time_used;
    int *p = new int[n];

    int i;
    i=0;
    while (i<n)
    {
        p[i] = i;
        i++;
    }
    start = clock();
    pFun(p, p+n);
    time_used = (float)(clock() - start)/CLOCKS_PER_SEC;
    printf("Ascending time: %f\n", time_used);

        i=0;
    while (i<n)
    {
        p[i] = n-i;
        i++;
    }
    start = clock();
    pFun(p, p+n);
    time_used = (float)(clock() - start)/CLOCKS_PER_SEC;
    printf("Desscending time: %f\n", time_used);

        i=0;
    while (i<n)
        p[i++] = rand();
    start = clock();
    pFun(p, p+n);
    time_used = (float)(clock() - start)/CLOCKS_PER_SEC;
    printf("Random time: %f\n", time_used);

    delete [] p;
}

使用实例:

View Code
int main()
{
    srand(time(NULL));
    while (1)
    {
        int n;
        cin >> n;
        if (n==0)
            break;
        printf("Heap sort:\n");
        pFun = HeapSort;
        OrderTest( n);
        PerformanceTest( n);
        printf("STL sort: \n");
        pFun = sort;
        PerformanceTest(n);

        return 0;
    }
}

 

 

posted on 2012-06-07 21:29  windflying  阅读(420)  评论(0编辑  收藏  举报