【C++】生成随机数写入文件中,并从文件中读取数据进行排序

#include<iostream>
using namespace std;
#include<stdlib.h>
#include<math.h>
#include<time.h>
#include<fstream>
#include<iomanip>
int num[100000000];
int n = 10000;
void CreatNum(int n) {
	ofstream ofs;
	ofs.open("D:\\data.txt", ios::out);
	srand(time(NULL));
	int t;
	for (int i = 0; i < n; i++) {
		t = rand();
		ofs << t << " ";
	}
	ofs.close();
}
void ReadFile() {
	ifstream ifs;
	ifs.open("D:\\data.txt", ios::in);
	int t, i = 0;
	while (ifs >> t) {
		if (ifs.eof())
			break;
		num[i++] = t;
	}
}
void bubble_sort(int num[], int n) {//冒泡排序
	int t;
	for (int i = n - 1; i > 0;i--) {
		for (int j = 0; j < i; j++) {
			if (num[j] > num[j + 1]) {
				t = num[j];
				num[j] = num[j + 1];
				num[j + 1] = t;
			}
		}
	}
}
void print(int num[], int n) {
	int count = 0;
	for (int i = 0; i < n; i++) {
		cout << num[i] << " ";
		count++;
		if (count % 10 == 0) {
			cout << "\n";
		}
	}
}
int main() {
	CreatNum(n);
	cout << "n \t重复次数 \t 总时间 \t 每次排序时间\n";
	cout << fixed << setprecision(8)<<setiosflags(ios::right);
	for (int i = 0; i < 5; i++) {
		ReadFile();
		int count = 0;
		double start = clock();
		do {
			count++;
			bubble_sort(num, n);
		} while (clock() - start < 1000);
		double elapsedMills = (clock() - start);
		cout << n;
		cout << setw(10) << count;
		cout << setw(20) << elapsedMills;
		cout<< setw(18)<<elapsedMills/count<<"\n";
	}
	
	
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值