一个排序测试的例子

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

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;
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值