您的位置:首页 > 其它

随机生成100万个数,排序后保存在文件中

2011-06-29 14:48 197 查看
随机生成100万个数,存储在文件out1.txt中,使用内部排序完成,并重新储存在文件out2.txt中。

(一)使用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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: