冒泡排序时间性能测量(最差情形)

#include<stdio.h>
#include<time.h>
#define MAX_SIZE 1001
#define SWAP(x,y,t) ((t)=(x),(x)=(y),(y)=t)

void sort(int [], int);

int main(void)
{
	int step=10;
	int a[MAX_SIZE];
	double duration;
	clock_t start;
	long repetitions;
	
	/*times for n=0,10,...1000 */
	printf("     n    time
");
	
	for(int n=0; n<=1000; n+=step)
	{
		/* get time for size n */
		repetitions = 0;
		start = clock();
		do{
			repetitions++;
			
			/* initialize with worst-case data */
			for(int i=0; i<n; i++)
				a[i]=n-i;
			
			sort(a, n);
		}while(clock()-start<1000);
		/* repeat until enough time has elapsed */
		
		duration=((double)(clock()-start)/CLOCKS_PER_SEC);
		duration/=repetitions;
		printf("%6d   %9d   %f
", n, repetitions, duration);
		if(n==100)
			step=100;
	}
	
	return 0;
}

void sort(int list[], int n)
{
	int min, temp;
	
	for(int i=0; i<n-1; i++)
	{
		min=i;
		for(int j=i+1; j<n; j++)
		{
			if(list[j] <list[min])
				min=j;
		}
		SWAP(list[i], list[min], temp);
	}
}

原文地址:https://www.cnblogs.com/WALLACE-S-BOOK/p/9732308.html