利用随机函数rand()生成50000个随机整数,分别使用起泡排序、选择排序、qsort排序方法对之排序,统计三种排序方法的运行时间差异
- 5.2.c
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include"sort.h"
#include<sys/time.h>
#include<unistd.h>
int main()
{
struct timeval tv1, tv2;
struct timezone tz;
int i, j;
int arr1[5000],arr2[5000], arr3[5000] ;
for(i=0; i<5000; i++)
{
j=1+(int)(100.0*rand()/(RAND_MAX+1.0));
arr1[i]=j;
arr2[i]=j;
arr3[i]=j;
}
//测试冒泡排序
gettimeofday(&tv1, &tz);
bubble_sort(arr1,5000);
gettimeofday(&tv2, &tz);
long dis1=0,dis2=0;
if(tv2.tv_usec<tv1.tv_usec)
{
dis1=(long)tv2.tv_sec-1-(long)tv1.tv_sec;
dis2=(long)tv2.tv_usec+1000000-(long)tv1.tv_usec;
}
else
{
dis1=(long)tv2.tv_sec-(long)tv1.tv_sec;
dis2=(long)tv2.tv_usec-(long)tv1.tv_usec;
}
printf("冒泡排序执行所需时间:%ld s, %ld us\n", dis1, dis2);
//测试选择排序
gettimeofday(&tv1, &tz);
select_sort(arr2,5000);
gettimeofday(&tv2, &tz);
printf("选择排序执行所需时间:%ld s, %ld us\n", tv2.tv_sec-tv1.tv_sec, tv2.tv_usec-tv1.tv_usec);
//测试qsort排序
gettimeofday(&tv1, &tz);
qsort(arr3, 5000, sizeof(arr3[0]), compare);
gettimeofday(&tv2, &tz);
printf("qsort执行所需时间: %ld s, %ld us\n", tv2.tv_sec-tv1.tv_sec, tv2.tv_usec-tv1.tv_usec);
return 0;
}
- sort.h
#include<stdlib.h>
#include<stdio.h>
void bubble_sort(int a[], int n);
void select_sort(int a[], int n);
int compare(const void *a, const void* b);
- bubblesort.c
#include<stdio.h>
#include<stdlib.h>
void bubble_sort ( int a[], int n )
{
for ( int i = 0; i < n - 1; i++ )
{
int isSorted = 1;
for ( int j = 0; j < n - 1 - i; j++ )
{
if ( a[j] > a[j + 1] )
{
isSorted = 0;
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
if ( isSorted == 1 )
break;
}
}
- selectsort.c
#include<stdio.h>
#include<stdlib.h>
void select_sort ( int a[], int n )
{
int i,j,t;
for(i=0; i<n-1; i++)
{
int m=i;
for(j=i; j<n; j++)
{
if(a[j]<a[m])
m=j;
}
if(m!=i)
{
t=a[i];
a[i]=a[m];
a[m]=t;
}
}
}
- comp.c
#include<stdlib.h>
#include<stdio.h>
int compare(const void *a, const void* b)
{
return *(int*)a-*(int*)b;
}
- makefile
5.2: 5.2.o bubblesort.o comp.o selectsort.o
gcc 5.2.o bubblesort.o comp.o selectsort.o -o 5.2
5.2.o: 5.2.c sort.h
gcc 5.2.c -c
bubblesort.o: bubblesort.c
gcc bubblesort.c -c
comp.o: comp.c
gcc comp.c -c
selectsort.o: selectsort.c
gcc selectsort.c -c
clean:
rm -f *~ *.o 5.2
11.执行结果: