您的位置:首页 > 其它

文件外部排序

2015-09-07 11:58 309 查看
问题摘要:

给外部文件里面没排好序的内容排序并将排好序的文件写入文件

例如:

没排序前:




排序后:



注意:我把文件是放在d:\数据.txt下面的,如果自己测试,要么更改路径,要么就要自己把要测试的文件放入该路径下。

思路很简单,就是将文件读进内存,然后排个序再写回去就行了。

#include <iostream>
#include <fstream>
using namespace std;
int num[100];
int  select_sort(int num[],int count){//选择排序,这里只能排整型数组,如果要排别的类型,需要更改
    for(int i=0;i<count;i++){
        for(int j=i+1;j<count;j++){
            if(num[j]<num[i]){
                int temp = num[i];
                    num[i] = num[j];
                    num[j] = temp;
            }
        }
    }
    //写入文件
    fstream f("d:数据.txt",ios::out);
    if(!f) cout<<"mistake";
    for(i=0;i<count;i++)  f<<num[i]<<" ";
    f.close();
    return 0;
}
void main()
{   
    int count=0;
    fstream f("d:\\数据.txt",ios::in);
    if(!f) cout<<"mistake";
    while(f>>num[count]&&!f.eof()){   //把文件读进内存,这个写的比较牛逼
        count++;
    }
    f.close();
    select_sort(num,count);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: