生成随机数文件并从文件中读取数据进行排序

 生成随机数文件

#include<bits/stdc++.h>
using namespace std;
int n,a[100000005]; 
void CreateNum(int a[],int n){
	ofstream op;
	op.open("C:\\Users\\Lenovo\\Desktop\\随机数.txt");
	srand((unsigned)time(NULL));
	for(int i=1;i<=n;i++){
		a[i]=rand()%1000000;
		op<<a[i]<<' ';
	}
	op.close();
	cout<<"随机数据文件生成完成"<<endl;
}
void QSort(int a[],int l,int r){
	if(l<r){
		int i=l,j=r,temp=a[l];
		while(i<j){
			while(i<j && a[j]>=temp) j--;
			if(i<j) a[i++]=a[j];
			while(i<j && a[i]<temp) i++;
			if(i<j) a[j--]=a[i];
		}
		a[i]=temp;
		QSort(a,l,i-1);
		QSort(a,i+1,r); 
	}
}
int main(){	
	ofstream op;
	op.open("C:\\Users\\Lenovo\\Desktop\\升序.txt");
	cin>>n;
	CreateNum(a,n);
	QSort(a,1,n);
	for(int i=1;i<=n;i++){
		op<<a[i]<<' ';
	}
	op.close();
	cout<<"升序数据文件生成完成"<<endl;
	return 0;
}

文件读取对数据进行排序

#include<iostream>
#include<fstream>
#include<time.h> 
using namespace std;
int a[100000005];//随机 
int b[100000005];//升序 
int p;
void ReadFile(){
	int x;
	p=1;
	ifstream op;
	op.open("C:\\Users\\Lenovo\\Desktop\\随机数.txt");
	while(op>>x){
		if(op.eof()) break;
		a[p++]=x;
	} 
	op.close();
	p=1;
	op.open("C:\\Users\\Lenovo\\Desktop\\升序.txt");
	while(op>>x){
		if(op.eof()) break;
		b[p++]=x;
	} 
	op.close();
	cout<<"数据读取完成"<<endl; 
}
void QSort(int s[],int l,int r){
	if(l<r){
		int i=l,j=r,temp=a[l];
		while(i<j){
			while(i<j && a[j]>=temp) j--;
			a[i++]=a[j];
			while(i<j && a[i]<temp) i++;
			a[j--]=a[i];
		}
		a[i]=temp;
		QSort(s,l,i-1);
		QSort(s,i+1,r); 
	}
} 
int main(){
	ReadFile();
	int n=p-1;//n个数 
	double st=clock();
	QSort(a,1,n);
	double end=clock();
	cout<<"随机数组排序时间:"<<end-st<<endl; 
	st=clock();
	QSort(b,1,n);
	end=clock();
	cout<<"升序数组排序时间:"<<end-st<<endl; 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41333844/article/details/85083832