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

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

 

 

相关文章:

  • 2021-09-02
  • 2022-03-06
  • 2021-07-19
  • 2021-11-20
  • 2022-01-11
  • 2021-05-17
  • 2022-02-27
  • 2021-12-06
猜你喜欢
  • 2022-01-16
  • 2021-06-08
  • 2022-12-23
  • 2022-01-22
  • 2021-06-02
  • 2022-01-25
  • 2022-01-23
相关资源
相似解决方案