随机生成100万个数,排序后保存在文件中
2011-06-29 14:48
211 查看
随机生成100万个数,存储在文件out1.txt中,使用内部排序完成,并重新储存在文件out2.txt中。
(一)使用STL中的qsort函数进行操作:
(二)递归实现qsort函数进行操作:
(一)使用STL中的qsort函数进行操作:
]#include "stdio.h" #include "string.h" #include "stdlib.h" #include "time.h" int a[1000000]; void load(char filename[]) //写文件 { int i; FILE *fp; fp=fopen(filename,"w"); if(fp==NULL) { printf("cannot open file/n"); return; } for(i=0;i<1000000;i++) fprintf(fp,"%d ",a[i]); } int cmp(const void *a, const void *b) { return (*(int*)a)-(*(int*)b); //从小到大进行排序 } void paixu() { qsort(a,1000000,sizeof(int),cmp); } int main(void) { int i; char filename[20]; srand( (unsigned)time( NULL ) ); //初始化随机数 for(i=0;i<1000000;i++) //打印出10个随机数 a[i]=rand(); strcpy(filename,"out1.txt"); load(filename); paixu();//快速排序 strcpy(filename,"out2.txt"); load(filename); system("pause"); return 0; }
(二)递归实现qsort函数进行操作:
]#include "string.h" #include "stdlib.h" #include "stdio.h" #include "time.h" int a[1000000]; void load(char filename[]) //写文件 { int i; FILE *fp; fp=fopen(filename,"w"); if(fp==NULL) { printf("cannot open file/n"); return; } for(i=0;i<1000000;i++) fprintf(fp,"%d ",a[i]); } int partitions(int a[],int low,int high) { int pivotkey=a[low]; //基准 while(low<high) { while(low<high && a[high]>=pivotkey) --high; a[low]=a[high]; while(low<high && a[low]<=pivotkey) ++low; a[high]=a[low]; } a[low]=pivotkey; return low; } void qsort(int a[],int low,int high) //快速排序 { int pivotkey; if(low<high) { //递归调用 pivotkey=partitions(a,low,high); qsort(a,low,pivotkey-1); qsort(a,pivotkey+1,high); } } int main(void) { int i; char filename[20]; srand( (unsigned)time( NULL ) ); //初始化随机数 for(i=0;i<1000000;i++) //打印出10个随机数 a[i]=rand(); strcpy(filename,"out1.txt"); load(filename); qsort(a,0,1000000); //快速排序 strcpy(filename,"out2.txt"); load(filename); system("pause"); return 0; }
相关文章推荐
- 随机生成100万个数,排序后保存在文件中
- 随机生成100万个数,排序后保存在文件中
- 随机生成100万个数,排序后保存在文件中
- 随机生成100万个数,排序后保存在文件中
- Python 随机生成100行1000列的0~5之间的数据,并保存到csv文件
- java生成随机uuid并保存到文件
- C++: 生成100万随机数, 排序后保存到文件中
- Java随机生成验证码图片,并且保存到文件系统中
- Java随机生成验证码图片,并且保存到文件系统中
- 生成随机码,保存随机文件.
- STL系列十一 随机三趣题——随机重排,文件中随机取一行,生成N个随机数。
- 如何让EditPlus保存文件时不生成.bak备份文件
- 面试题: 随机生成1-100的100个元素的数组,并按最快的排序算法排序,并打印出来
- 如何设置EditPlus保存时不生成bak文件
- C++文本查询程序 不要定义类和智能指针管理数据 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- java 中 excel生成并文件下载保存到本地(三)
- asp生成htm文件。用xmlhttp得到源代码。然后用steam流打开保存源代码
- VS2005 保存文件、向导生成代码 速度变慢的解决方案
- Drupal上把phpExcel生成的Excel文件保存到Drupal文件系统
- 根据当前文件夹下所有文件随机自动生成训练和测试样本列表