统计三种排序方法的运行时间差异

利用随机函数rand()生成50000个随机整数,分别使用起泡排序、选择排序、qsort排序方法对之排序,统计三种排序方法的运行时间差异

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

  1. 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);

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

  1. 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;
       }
   }
}
  1. comp.c
#include<stdlib.h>
#include<stdio.h>

int compare(const void *a, const void* b)
{
	return *(int*)a-*(int*)b;
}
  1. 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.执行结果:

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值