笨笨的冒泡排序

说到排序算法有很多种,我这里也不献丑了,其中最差的估计就是冒泡排序了,但是作为CPU测试程序已经够用:

/* File Name : BubbleSort.c */
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

#define SIZE 100000
main()
{
    int i,j,temp;
    int a[SIZE];
    char buf[32];
    time_t tmp=time(NULL);
    for(i=0;i<SIZE;i++)
    {
        a[i]=rand();
    }
    strftime(buf,32,"%Y-%m-%d %H:%M:%S",localtime(&tmp));
    printf("%s BubbleSort Begin !\n",buf);
    for(j=0;j<=SIZE-1;j++)
    {
        for (i=0;i<SIZE-j;i++)
            if (a[i]>a[i+1])
            {
                temp=a[i];
                a[i]=a[i+1];
                a[i+1]=temp;
            }
    }
    tmp=time(NULL);
    strftime(buf,32,"%Y-%m-%d %H:%M:%S",localtime(&tmp));
    printf("%s BubbleSort Done  !\n" , buf);
}

SIZE 是定义对多大的随机数数组进行冒泡排序,我这里定义是10万个,通常测试持续几十秒到一分钟。

输出是如下:

2010-08-27 16:26:03 BubbleSort Begin !
2010-08-27 16:26:36 BubbleSort Done  !

将两个时间相减就是测试时间了。

用法超简单:

[root@logserver c]# vim BubbleSort.c 
# ...
# 插入代码
# ...
[root@logserver c]# gcc ./BubbleSort.c -o BubbleSort -O
[root@logserver c]# ./BubbleSort   
2010-08-27 20:02:45 BubbleSort Begin !
2010-08-27 20:03:19 BubbleSort Done  !
也可以自己测量时间:
[root@logserver c]# time ./BubbleSort 
2010-08-27 16:26:03 BubbleSort Begin !
2010-08-27 16:26:36 BubbleSort Done  !

real    0m33.831s
user    0m33.824s
sys     0m0.000s
原文地址:https://www.cnblogs.com/killkill/p/1810378.html