C++ 冒泡排序时间复杂度测试

#include <iostream>
#include <ctime>
#include <stdlib.h>
#include <cmath>
#include <fstream>
#include<time.h>
using namespace std;
void bubblesort(int a[], int n) {
	
	int i, j;
	int buf = 0;
		for (i = 0; i < n - 1; ++i)  //比较n-1轮
	{
		for (j = 0; j < n - 1 - i; ++j)  //每轮比较n-1-i次,
		{
			if (a[j] < a[j + 1])
			{
				buf = a[j];
				a[j] = a[j + 1];
				a[j + 1] = buf;
			}
		}
	}
}

int main() {
	int num;
	int allnum;
	srand((unsigned int)(time(NULL)));//生成随机数
	int n;
	cout << "请输入数组大小" << endl;
	cin >> n;
	int a[100000];//开数组

	for (int i = 0; i < n; i++) {//把随机数存入数组

		allnum = 0;

		for (int j = 0; j < 6; j++) {

			num = rand() % 10;
			allnum += num * pow(10, j);
		}

		a[i] = allnum;
	}
clock_t start, finish;
	double totaltime;
	start = clock();
	//计时开始
	bubblesort(a, n);//冒泡排序
	
ofstream  ofs; //2.创建流对象 


	ofs.open("文件.txt", ios::out);//3.打开文件
	
	
	for (int i = 0; i < n; i++) {

		cout << a[i] << endl;
		ofs << a[i] << endl;
	}finish = clock();
	totaltime = (double)(finish - start) / CLOCKS_PER_SEC;
	cout << "\n此程序的运行时间为" << totaltime << "秒!" << endl;
	ofs.close();//4.关闭文件
	
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值