第一个排序函数 sort1() 为冒泡排序的典型实现,第二和第三个为改进后的排序函数
#include <stdio.h>
#include <time.h>
#define LEN 20000
double sort1(int *,int);
double sort2 (int *,int);
double sort3 (int *,int );
int main(int argc,char *argv[])
{
int a[LEN],b[LEN],c[LEN];
int i,j;
//clock_t begin, end;
double spend1 = 0,spend2 = 0,spend3 = 0;
//初始化三个一模一样的数组
for(i = 0; i < LEN; i++)
{
a[i] = (int)(rand()%10000);
c[i] = b[i] = a[i];
}
//分别调用三种排序函数
spend1 = sort1(a,LEN);
spend2 = sort2(b,LEN);
spend3 = sort3(c,LEN);
//输出排序的最后一百个
for(i = LEN-100; i < LEN; i++)
{
printf("%d\t",a[i]);
if((i + 1) % 10 == 0)
{
printf("\n");
}
}
//输出消耗的时间
printf("sort1 spend %lf s\n",spend1);
for(i = LEN-100; i < LEN; i++)
{
printf("%d\t",b[i]);
if((i + 1) % 10 == 0)
{
printf("\n");
}
}
printf("sort2 spend %lf s\n",spend2);
for(i = LEN-100; i < LEN; i++)
{
printf("%d\t",c[i]);
if((i + 1) % 10 == 0)
{
printf("\n");
}
}
printf("sort3 spend %lf s\n",spend3);
return 0;
}
double sort1 (int*a,int len)
{
int i,j;
double spend;
clock_t begin, end;
//开始计时
begin = clock();
for(i = 0; i < len-1; i++)
{
for(j = i + 1; j < len; j++)
{
if(a[i] > a[j])
{
a[i] = a[i] + a[j];
a[j] = a[i] - a[j];
a[i] = a[i] - a[j];
}
}
}
//结束计时
end = clock();
//计算消耗的时间
spend = (double)(end - begin) / CLOCKS_PER_SEC;
return spend;
}
double sort2 (int*a,int len)
{
int i,j;
double spend;
clock_t begin, end;
begin = clock();
for(i = 0; i < len-1; i++)
{
for(j = i; j < len-1; j++)
{
if(a[j] > a[j+1])
{
a[j] = a[j] + a[j+1];
a[j+1] = a[j] - a[j+1];
a[j] = a[j] - a[j+1];
}
}
}
end = clock();
spend = (double)(end - begin) / CLOCKS_PER_SEC;
return spend;
}
double sort3 (int*a,int len)
{
int i,j;
double spend;
clock_t begin, end;
int isEnd = 0;
begin = clock();
for(i = 0; i < len-1 && !isEnd; i++)
{
isEnd = 1;
for(j = i; j < len-1; j++)
{
if(a[j] > a[j+1])
{
isEnd = 0;
a[j] = a[j] + a[j+1];
a[j+1] = a[j] - a[j+1];
a[j] = a[j] - a[j+1];
}
}
}
end = clock();
spend = (double)(end - begin) / CLOCKS_PER_SEC;
return spend;
}