DS001-Test running time of bubble sort

This program demonstrates how to test the running time of a program.

Take the bubble sort algorithm as an example.

#include "time.h"   //与时间相关的函数
#include "stdlib.h"   //rand()函数在此库中
#include "stdio.h" //输入输出相关函数 
void BubbleSort(int *a, int n)
{//冒泡排序, a是指针,代表连续空间的首地址,n表示有n个元素
	for(int i=1;i<=n-1;i++)
	{
		for(int j=0;j<=n-i-1;j++)
		{
			if(a[j]>a[j+1])
			{
				int t;
				t=a[j];
				a[j]=a[j+1];
				a[j+1]=t;
			}
		}
	}
}

int main(  )
{
	time_t start, stop;
	int n;
	int data_num[]={10000,30000,60000,90000};//问题规模 
	int j;
	for(j=0;j<4;j++)
	{
		n=data_num[j];//问题规模 
		int a[n]={0};
		for(int i=0;i<n;i++)
			a[i]=rand();
		
	    start=time (0);	//单位是秒
		BubbleSort(a,n);
		stop=time (0);			
		time_t runTime = stop - start;
		printf ( "%d %d\n" , n,runTime );
	}
	return 0;
}

 operation result:

Among them, the first column is the number of data, and the second column is the execution time of the corresponding bubble sort.

Using the first column as the abscissa and the second column as the ordinate, make a scatter chart in Excel:

The figure is similar to the shape of the y=n*n function.

The time complexity of the algorithm, in O notation, is exactly: O(n*n)

Guess you like

Origin blog.csdn.net/weixin_43917370/article/details/108328981