笨笨的冒泡排序
說到排序算法有很多種,我這里也不獻丑了,其中最差的估計就是冒泡排序了,但是作為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
浙公網安備 33010602011771號