实现外部归并排序
Implementing External Merge Sort
我知道外部合并排序和它是如何工作的。但目前我被困在执行它。我已经编写了代码来排序和合并数组,但我面临的问题,而读取和写入数据从/到文件,我想在c++中实现以下方法:
1. int * read(int s, int e) : This method should read from file all the number
starting from 's' till 'e' and return the array
2. write(int a[], int s, int e) : This method should write to file the input
array by replacing the numbers from s to e.
例如。
Given file has the following numbers:
1
2
3
4
5
6
read(0, 2) should return [1,2,3]
write([4,5,6], 0, 2) should update the file to :
4
5
6
4
5
6
我如何实现这两个方法?
您应该做的第一件事就是停止使用原始指针。
std::vector<int>
将同样高效,并且更不容易出错。
第二,文件格式很重要。我将假设一个包含32位带符号整数的二进制文件。
读写签名现在是:
std::vector<int> read( std::ifstream const& f, int offset );
void write( std::ofstream& f, int offset, std::vector<int> const& data );
ifstream
和ofstream
有寻法,特别是ifstream
有seekg
, ofstream
有seekp
。
ifstream.read( char* , length )
在当前get位置(由seekg
设置,由read
提高)从文件中读取length
字节。如果你不关心你的文件的内存布局,你可以从std::vector<int>
中获得.data()
,重新解释为char*
,然后继续到read( reinterpret_cast<char*>(vec.data()), sizeof(int)*vec.size() )
一次读取缓冲区。
ofstream
有一个类似的write
方法,其工作方式大致相同。
虽然将数据直接写入磁盘并返回是危险的,但在大多数(每个?)实现中,在相同的执行会话中(甚至可能在会话之间)写入和读取数据是安全的。如果数据打算在会话之间持久化,或者它是代码的输出/输入,请更加小心。
没有c++标准函数跳转到文件中的行。因此,您必须逐行读取文件(例如使用getline)。http://www.cplusplus.com/reference/string/string/getline/)。
就我所记得的,外部合并排序(旧的,为有几个磁带驱动器的计算机设计的),当用于单独的文件时,不需要像你这样的接口-你可以按顺序工作。